|
1 | 1 | #!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
2 | 3 | # |
3 | | -# Simple Bot to reply Telegram messages |
| 4 | +# Simple Bot to reply to Telegram messages |
4 | 5 | # Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com> |
5 | 6 | # |
6 | 7 | # This program is free software: you can redistribute it and/or modify |
|
19 | 20 |
|
20 | 21 | import logging |
21 | 22 | import telegram |
| 23 | +from time import sleep |
22 | 24 |
|
23 | | - |
24 | | -LAST_UPDATE_ID = None |
| 25 | +try: |
| 26 | + from urllib.error import URLError |
| 27 | +except ImportError: |
| 28 | + from urllib2 import URLError # python 2 |
25 | 29 |
|
26 | 30 |
|
27 | 31 | def main(): |
28 | | - global LAST_UPDATE_ID |
| 32 | + update_id = None |
29 | 33 |
|
30 | 34 | logging.basicConfig( |
31 | 35 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') |
32 | 36 |
|
33 | 37 | # Telegram Bot Authorization Token |
34 | 38 | bot = telegram.Bot('TOKEN') |
35 | 39 |
|
36 | | - # This will be our global variable to keep the latest update_id when requesting |
37 | | - # for updates. It starts with the latest update_id if available. |
38 | | - try: |
39 | | - LAST_UPDATE_ID = bot.getUpdates()[-1].update_id |
40 | | - except IndexError: |
41 | | - LAST_UPDATE_ID = None |
42 | | - |
43 | 40 | while True: |
44 | | - echo(bot) |
45 | | - |
46 | | - |
47 | | -def echo(bot): |
48 | | - global LAST_UPDATE_ID |
49 | | - |
50 | | - # Request updates after the last updated_id |
51 | | - for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=10): |
52 | | - # chat_id is required to reply any message |
| 41 | + try: |
| 42 | + update_id = echo(bot, update_id) |
| 43 | + except telegram.TelegramError as e: |
| 44 | + # These are network problems with Telegram. |
| 45 | + if e.message in ("Bad Gateway", "Timed out"): |
| 46 | + sleep(1) |
| 47 | + else: |
| 48 | + raise e |
| 49 | + except URLError as e: |
| 50 | + # These are network problems on our end. |
| 51 | + sleep(1) |
| 52 | + |
| 53 | + |
| 54 | +def echo(bot, update_id): |
| 55 | + |
| 56 | + # Request updates after the last update_id |
| 57 | + for update in bot.getUpdates(offset=update_id, timeout=10): |
| 58 | + # chat_id is required to reply to any message |
53 | 59 | chat_id = update.message.chat_id |
54 | | - reply_text = update.message.text |
| 60 | + update_id = update.update_id + 1 |
| 61 | + message = update.message.text |
55 | 62 |
|
56 | | - if reply_text: |
57 | | - # Reply the message |
| 63 | + if message: |
| 64 | + # Reply to the message |
58 | 65 | bot.sendMessage(chat_id=chat_id, |
59 | | - text=reply_text) |
| 66 | + text=message) |
60 | 67 |
|
61 | | - # Updates global offset to get the new updates |
62 | | - LAST_UPDATE_ID = update.update_id + 1 |
| 68 | + return update_id |
63 | 69 |
|
64 | 70 |
|
65 | 71 | if __name__ == '__main__': |
|
0 commit comments