How to send an image from a telegram bot

前端 未结 4 1867
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 13:17

I have my bot working by now, but the thing is it can only send text. I have seen in the Bot API there are functions to send photos, videos... but I can\'t get it to work. S

相关标签:
4条回答
  • 2020-12-22 14:10

    I have included two functions, one is good for sending local images, the other one is good for sending remote images.

    def sendImage():
        url = "https://api.telegram.org/bot<Token>/sendPhoto";
        files = {'photo': open('/path/to/img.jpg', 'rb')}
        data = {'chat_id' : "YOUR_CHAT_ID"}
        r= requests.post(url, files=files, data=data)
        print(r.status_code, r.reason, r.content)
    
    def sendImageRemoteFile(img_url):
        url = "https://api.telegram.org/bot<Token>/sendPhoto";
        remote_image = requests.get(img_url)
        photo = io.BytesIO(remote_image.content)
        photo.name = 'img.png'
        files = {'photo': photo}
        data = {'chat_id' : "YOUR_CHAT_ID"}
        r= requests.post(url, files=files, data=data)
        print(r.status_code, r.reason, r.content)
    
    0 讨论(0)
  • 2020-12-22 14:14

    Before sending the photo, you have to do output.seek(0) to put the cursor back to the beginning of the file, else it will be read as zero

    0 讨论(0)
  • 2020-12-22 14:23

    The solution is

    elif 'Hi' in text:
    reply(img=urllib2.urlopen('img url').read())
    

    or

    if text == 'help':
                reply(img=urllib2.urlopen('img url').read())
    
    0 讨论(0)
  • I understand the question. Here's the answer:

            def sendImageFromUrl(url):
                #this tweak added if request image failed
                headers = {'user-agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'}
                response = requests.get(url, headers=headers)
                #response = requests.get(url)
                output = StringIO(response.content)
                img = Image.open(output)
                img.save(output, 'JPEG')
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                    ('caption', 'Your Caption'),
                ], [
                    ('photo', 'image.jpg', output.getvalue()),
                ])
    

    Make sure your server does have python module: requests.

    You can download here: https://pypi.python.org/pypi/requests#downloads

    And put in your application like this

    /myapp/app.yaml
    /myapp/main.py
    /myapp/requests/packages/
    /myapp/requests/__init__.py
    /myapp/requests/adapters.py
    etc...
    

    Credit: https://stackoverflow.com/a/17128168/1097372

    Put in main.py after line 10

    import requests
    from StringIO import StringIO
    
    0 讨论(0)
提交回复
热议问题