python-telegram-bot/examples/echobot.py

57 lines
1.5 KiB
Python
Raw Normal View History

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple Bot to reply to Telegram messages.
This is built on the API wrapper, see echobot2.py to see the same example built
on the telegram.ext bot framework.
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
2016-06-12 15:30:56 +02:00
update_id = None
def main():
"""Run the bot."""
2016-06-12 15:30:56 +02:00
global update_id
# 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:
2017-05-19 21:49:01 +02:00
update_id = bot.get_updates()[0].update_id
except IndexError:
update_id = None
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
while True:
try:
2016-06-12 15:30:56 +02:00
echo(bot)
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
2016-06-12 15:30:56 +02:00
def echo(bot):
"""Echo the message the user sent."""
2016-06-12 15:30:56 +02:00
global update_id
# Request updates after the last update_id
2017-05-19 21:49:01 +02:00
for update in bot.get_updates(offset=update_id, timeout=10):
update_id = update.update_id + 1
2015-08-20 19:58:57 +02:00
if update.message: # your bot can receive updates without messages
# Reply to the message
update.message.reply_text(update.message.text)
2015-08-20 19:58:57 +02:00
if __name__ == '__main__':
main()