Skip to content

Instantly share code, notes, and snippets.

@sksullivan
Created June 30, 2015 03:55
Show Gist options
  • Save sksullivan/d699cbbbc3e2c3c6ec69 to your computer and use it in GitHub Desktop.
Save sksullivan/d699cbbbc3e2c3c6ec69 to your computer and use it in GitHub Desktop.
Quick, sub 30 line image search bot for Telegram Messenger
import requests
import time
import urllib
if __name__ == '__main__':
print("Starting ImageSearchBot... Search for images using /<search query> in a chat with ImageSearchBot.")
lastID = 0
while (1):
# Ask telegram.org for updates sent to our bot. We use our bot credentials and the number for the last update ID we've seen.
reply = requests.get("https://api.telegram.org/bot00000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/getUpdates?offset={}".format(lastID))
updates = reply.json()['result']
if (len(updates) > 0):
for update in updates:
# If the update was a message for us...
if 'text' in update['message']:
# perform an image search using the message text, escaping the search string.
imageSearchReply = requests.get("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q={}%20".format(urllib.quote(update['message']['text'])))
# Grab the image URL from the response.
imageURL = imageSearchReply.json()['responseData']['results'][0]['url']
# Get the ID for the telegram chat from which the message was sent...
chatID = update['message']['chat']['id']
# and send a message to that chat with our image URL! (again, escaped)
requests.get("https://api.telegram.org/bot00000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/sendMessage?chat_id={}&text=Your%20image%20{}".format(chatID,urllib.quote_plus(imageURL)))
# Finally, update the last update ID we have seen.
lastID = update['update_id'] if update['update_id'] > lastID else lastID
# Just to make sure we don't process a request twice, increment the last update ID each time we have messages.
lastID += 1
time.sleep(10)
@vkedwardli
Copy link

Hi, are you the author of @ImageSearchBot? It would be great if there is a default quality setting for the query results, so duplicated image won't flood the chat room

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment