python-telegram-bot/examples/legacy/echobot.py

54 lines
1.4 KiB
Python
Raw Normal View History

#!/usr/bin/env python
# -*- coding: utf-8 -*-
2015-08-11 21:58:17 +02:00
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
import logging
import telegram
2016-02-09 15:28:54 +01:00
from telegram.error import NetworkError, Unauthorized
from time import sleep
def main():
# Telegram Bot Authorization Token
bot = telegram.Bot('TOKEN')
# get the first pending update_id, this is so we can skip over it in case
# we get an "Unauthorized" exception.
try:
update_id = bot.getUpdates()[0].update_id
except IndexError:
update_id = None
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
while True:
try:
update_id = echo(bot, update_id)
2016-02-09 15:28:54 +01:00
except NetworkError:
sleep(1)
2016-02-09 15:28:54 +01:00
except Unauthorized:
# The user has removed or blocked the bot.
update_id += 1
def echo(bot, update_id):
# Request updates after the last update_id
for update in bot.getUpdates(offset=update_id, timeout=10):
# chat_id is required to reply to any message
2015-08-20 19:58:57 +02:00
chat_id = update.message.chat_id
update_id = update.update_id + 1
message = update.message.text
2015-08-20 19:58:57 +02:00
if message:
# Reply to the message
bot.sendMessage(chat_id=chat_id, text=message)
2015-08-20 19:58:57 +02:00
return update_id
if __name__ == '__main__':
main()