1

完整的Python新手,对不起!

我正在使用 Telebot 入门工具包 ( https://github.com/yukuku/telebot ),它将回复处理为:

elif 'who are you' in text:
        reply('telebot starter kit, created by yukuku: https://github.com/yukuku/telebot')

我能够让它回复一张图片:

elif 'Test1' in text:
           reply(img=urllib2.urlopen('https://i.ytimg.com/vi/VC8H5B2YVCY/maxresdefault.jpg').read())

但不能发送动画 GIF。根据上述作为 img 发送使用的是静态的 sendPhoto

我确定它必须是添加 InlineQueryResultGif 类并在 reply() 中调用它的情况,但我已经尝试了很多很多方法,但我没有取得任何进展

帮助!

编辑以显示一些尝试:

首先,我尝试编辑已经用于发送 img 的 elif 参数:

elif gif:
            gif = multipart.post_multipart(BASE_URL + 'InlineQueryResultGif', [
                ('chat_id', str(chat_id)),
                ('reply_to_message_id', str(message_id)),
            ], [
                ('gif', 'image.gif', gif),
            ])

然后简单地将回复更改为:

elif 'Test4' in text:
        reply(gif=urllib2.urlopen('http://www.reactiongifs.us/wp-content/uploads/2014/08/popcorn_indiana_jones.gif').read())

然后我尝试添加 InlineQueryResultGif 类本身:

class InlineQueryResult:
pass

class InlineQueryResultGif(InlineQueryResult):
""" Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with
optional caption. Alternatively, you can provide message_text to send it instead of the animation.
Attributes:
    id                          (str)    :Unique identifier of this result
    gif_url                     (str)    :A valid URL for the GIF file. File size must not exceed 1MB
    gif_width                   (int)    :*Optional.* Width of the GIF
    gif_height                  (int)    :*Optional.* Height of the GIF
    thumb_url                   (str)    :*Optional.* URL of a static thumbnail for the result (jpeg or gif)
    title                       (str)    :*Optional.* Title for the result
    caption                     (str)    :*Optional.* Caption of the GIF file to be sent
    message_text                (str)    :*Optional.* Text of a message to be sent instead of the animation
    parse_mode                  (str)    :*Optional.* Send “Markdown”, if you want Telegram apps to show bold,
                                                      italic and inline URLs in your bot's message.
    disable_web_page_preview    (bool)   :*Optional.* Disables link previews for links in the sent message
"""

def __init__(self, id, gif_url,
             gif_width=None, gif_height=None, thumb_url=None, title=None,
             caption=None, message_text=None, parse_mode=None, disable_web_page_preview=None):
    self.type = 'gif'
    self.id = id
    self.gif_url = gif_url
    self.gif_width = gif_width
    self.gif_height = gif_height
    self.thumb_url = thumb_url
    self.title = title
    self.caption = caption
    self.message_text = message_text
    self.parse_mode = parse_mode
    self.disable_web_page_preview = disable_web_page_preview

并试图在回复中调用它:

elif 'Test2' in text:
        reply(InlineQueryResultGif('http://www.reactiongifs.us/wp-content/uploads/2014/08/popcorn_indiana_jones.gif'))

以及上述的许多不同版本。没有任何工作

4

4 回答 4

1

在实现内联的东西之前,你几乎第一次就做对了,除了你需要使用sendDocument

elif gif:
        resp = multipart.post_multipart(BASE_URL + 'sendDocument', [
            ('chat_id', str(chat_id)),
            ('reply_to_message_id', str(message_id)),
        ], [
            ('gif', 'image.gif', gif),
        ])

...然后urllib2像这样读取 gif:

elif 'Test2' in text:
    reply(gif=urllib2.urlopen('http://www.reactiongifs.us/wp-content/uploads/2014/08/popcorn_indiana_jones.gif').read())

您也可以对本地文件执行此操作,但我发现在处理相对路径(例如使用 Google AppEngine)时,该file://功能非常令人沮丧。urllib2对于本地文件,我只是使用urllib,如下所示:

elif 'Test2' in text:
    reply(gif=urllib.urlopen('images/animated.gif').read())
于 2016-09-28T21:51:50.027 回答
0

我正在使用python-telegram-bot这就是我处理这个问题的方式。

def sendImage(bot, update, dataval): # Funtion to send images or gifs the proper way
  val = dataval.rsplit('.', 1)[1]
  if val == 'gif':
    # Send a gif
    bot.sendDocument(chat_id=update.message.chat_id, document = dataval)
  elif val == 'webm':
    bot.sendMessage(chat_id=update.message.chat_id, text = "The item attempted to be sent is unsupported at the moment.")
  else:
    # Send a Picture
    bot.sendPhoto(chat_id=update.message.chat_id, photo=dataval)

在上面的示例中,我将 url 传递给 dataval 变量中的函数。我已经好几个月没有重新访问它了,所以,现在可能支持 webm。此外,还有一种方法可以通过存储在电报服务器上的 id 发送图像,但是,我不知道如何使用该方法。

于 2016-06-16T01:15:17.493 回答
0

如果可以,请尝试使用此 Python 库进行电报

https://github.com/python-telegram-bot/python-telegram-bot

有了这个,您可以轻松地发送动画 GIF sendDocument

bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
bot.sendDocument(chat_id=chat_id, document=image_url)
于 2016-03-18T06:47:54.643 回答
0

我的方法(使用python-telegram-bot)这就是我完成这项工作的方式。

def get_gif_data():
    """ Generates binary data to post animation """
    files = []
    for file in os.listdir("."):
        if file.endswith(".gif"):
            files.append(file)
    new_gif = files[randrange(len(files))] 
    logger.info(f"-== Used gif file: {new_gif}")
    animation = open(new_gif, 'rb').read()    
    return animation


def echo_gif(update: Update, context: CallbackContext) -> None:
    """Echo to /gif with gif"""

    context.bot.sendAnimation(chat_id=update.message.chat_id,
               animation=get_gif_data(), ## that's just data from local gif file
               caption='That is your gif!',
               )
    print("GIF!")
    return    


于 2021-09-12T20:07:43.750 回答