From 582bb61e5b2740bf837a12296557cff7ba7d0228 Mon Sep 17 00:00:00 2001 From: Leandro Toledo Date: Sun, 12 Jul 2015 09:54:03 -0300 Subject: [PATCH] Adding echobot example and fix IOError typo --- examples/echobot.py | 38 ++++++++++++++++++++++++++++++++++++++ telegram/bot.py | 4 +++- 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 examples/echobot.py diff --git a/examples/echobot.py b/examples/echobot.py new file mode 100644 index 000000000..5a18c2093 --- /dev/null +++ b/examples/echobot.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +'''Simple Bot to reply Telegram messages''' + +import telegram +import time + +# Telegram Bot Authorization Token +bot = telegram.Bot('120405045:AAEAQ3EcfZ3NztkUbOkMOwCxXdDikEW1VZE') + +# This will be our global variable to keep the latest update_id when requesting +# for updates. It starts with the latest update_id available. +LAST_UPDATE_ID = bot.getUpdates()[-1].update_id + + +def echo(): + global LAST_UPDATE_ID + + # Request updates from last updated_id + for update in bot.getUpdates(offset=LAST_UPDATE_ID): + if LAST_UPDATE_ID < update.update_id: + # chat_id is required to reply any message + chat_id = update.message.chat_id + message = update.message.text + + if (message): + # Reply the message + bot.sendMessage(chat_id=chat_id, + text=message) + + # Updates global offset to get the new updates + LAST_UPDATE_ID = update.update_id + + +if __name__ == '__main__': + while True: + echo() + time.sleep(5) diff --git a/telegram/bot.py b/telegram/bot.py index 313728c66..509839cc2 100644 --- a/telegram/bot.py +++ b/telegram/bot.py @@ -589,7 +589,9 @@ class Bot(object): url, urllib.urlencode(data) ).read() - except urllib.IOError as e: + except IOError as e: + raise TelegramError(str(e)) + except urllib2.HTTPError as e: raise TelegramError(str(e)) except urllib2.URLError as e: raise TelegramError(str(e))