【问题标题】:Telegram Bot Random Images (How to send random images with Telegram-Bot)Telegram Bot 随机图像(如何使用 Telegram-Bot 发送随机图像)
【发布时间】:2018-02-13 10:20:21
【问题描述】:
const TeleBot = require('telebot');


const bot = new TeleBot({
token: 'i9NhrhCQGq7rxaA' // Telegram Bot API token.
});

bot.on(/^([Hh]ey|[Hh]oi|[Hh]a*i)$/, function (msg) {
return bot.sendMessage(msg.from.id, "Hello Commander");
});

var Historiepics = ['Schoolfotos/grr.jpg', 'Schoolfotos/boe.jpg', 
'Schoolfotos/tobinsexy.jpg'];


console.log('Historiepics')
console.log(Math.floor(Math.random() * Historiepics.length));
var foto = Historiepics[(Math.floor(Math.random() * Historiepics.length))];

bot.on(/aap/, (msg) => {
return bot.sendPhoto(msg.from.id, foto);
});



bot.start();

我从中得到的结果每次都只是一张图片,但如果我要求另一张随机图片,它会一直向我显示同一张图片而不会改变。

【问题讨论】:

    标签: random telegram telegram-bot


    【解决方案1】:

    我最近发现了这一点,因此我将为遇到此问题的任何人提供答案。

    问题在于 Telegram 的缓存。他们在服务器端缓存图像,这样他们就不必对同一个 url 执行多个请求。这可以保护他们免于因太多请求而被列入黑名单,并使事情变得更快捷。

    不幸的是,如果您使用像 The Cat API 这样的 API,这意味着您将一遍又一遍地发送相同的图像。最简单的解决方案就是以某种方式使链接每次都有些不同。这很容易通过将当前纪元时间包含在 url 中来实现。

    对于您使用 javascript 的示例,这可以通过以下修改来完成

    bot.on(/aap/, (msg) => {
      let epoch = (new Date).getTime();
      return bot.sendPhoto(msg.from.id, foto + "?time=" + epoch);
    });
    

    或类似的东西。要点是,只要 URL 不同,您就不会收到缓存的结果。另一种选择是下载文件,然后在本地发送。如果您将 serverDownload 选项传递给 sendPhoto,这就是 Telebot 所做的。

    【讨论】:

      猜你喜欢
      • 2019-11-18
      • 2020-05-13
      • 2021-11-12
      • 2021-09-14
      • 2015-11-26
      • 2018-06-07
      • 1970-01-01
      • 2020-08-18
      • 2016-01-10
      相关资源
      最近更新 更多