Matt Ryan
Matt Ryan

Reputation: 21

Telegram Python chatbot - replying with an animated gif

complete Python newbie, sorry!

I'm using the Telebot starter kit (https://github.com/yukuku/telebot) which handles replies as:

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

I was able to get it to reply with an image with:

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

But cannot send animated gifs. Sending as an img per above uses sendPhoto which is static

I'm sure it has to be a case of adding the InlineQueryResultGif class and calling it inside a reply() but I've tried lots and lots of ways of doing that but I'm not making any progress

Help!

EDIT to show some attempts:

Firstly I tried editing the elif argument that was already in place for sending the img:

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),
            ])

and then simply changing the reply to be:

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

Then I've tried adding the InlineQueryResultGif class itself:

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

And tried to call it inside the reply:

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

And lots of different versions of the above. Not getting anything to work

Upvotes: 2

Views: 12346

Answers (4)

Constantine Kurbatov
Constantine Kurbatov

Reputation: 905

My approach (using python-telegram-bot) and this is how I got this work.

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    


Upvotes: 0

rubynorails
rubynorails

Reputation: 627

You almost had it right the first time before implementing the inline stuff, except you need to use 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),
        ])

...and then use urllib2 to read the gif like so:

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

You can also do this with local files, but I found the file:// functionality in urllib2 to be quite frustrating when dealing with relative paths (such as with Google AppEngine). For local files, I just use urllib instead, like so:

elif 'Test2' in text:
    reply(gif=urllib.urlopen('images/animated.gif').read())

Upvotes: 1

Eric Niconovich
Eric Niconovich

Reputation: 11

I'm using python-telegram-bot and this is how I approached this.

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)

In my example above, I pass a url to the function in the dataval variable. I haven't re-visited this in many months, so, its possible that webm's are supported now. Also, there is a way to send images by their id as stored on telegram's servers, however, I do not know how to use that method.

Upvotes: 1

lamirap
lamirap

Reputation: 520

If you can, try using this Python library for telegram

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

With this you can easily send animated gifs with sendDocument:

bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
bot.sendDocument(chat_id=chat_id, document=image_url)

Upvotes: 0

Related Questions