rawapibot.py

This example uses only the pure, “bare-metal” API wrapper.

 1#!/usr/bin/env python
 2# pylint: disable=wrong-import-position
 3"""Simple Bot to reply to Telegram messages.
 4
 5This is built on the API wrapper, see echobot.py to see the same example built
 6on the telegram.ext bot framework.
 7This program is dedicated to the public domain under the CC0 license.
 8"""
 9import asyncio
10import contextlib
11import logging
12from typing import NoReturn
13
14from telegram import __version__ as TG_VER
15
16try:
17    from telegram import __version_info__
18except ImportError:
19    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]  # type: ignore[assignment]
20
21if __version_info__ < (20, 0, 0, "alpha", 1):
22    raise RuntimeError(
23        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
24        f"{TG_VER} version of this example, "
25        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
26    )
27from telegram import Bot
28from telegram.error import Forbidden, NetworkError
29
30logging.basicConfig(
31    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
32)
33logger = logging.getLogger(__name__)
34
35
36async def main() -> NoReturn:
37    """Run the bot."""
38    # Here we use the `async with` syntax to properly initialize and shutdown resources.
39    async with Bot("TOKEN") as bot:
40        # get the first pending update_id, this is so we can skip over it in case
41        # we get a "Forbidden" exception.
42        try:
43            update_id = (await bot.get_updates())[0].update_id
44        except IndexError:
45            update_id = None
46
47        logger.info("listening for new messages...")
48        while True:
49            try:
50                update_id = await echo(bot, update_id)
51            except NetworkError:
52                await asyncio.sleep(1)
53            except Forbidden:
54                # The user has removed or blocked the bot.
55                update_id += 1
56
57
58async def echo(bot: Bot, update_id: int) -> int:
59    """Echo the message the user sent."""
60    # Request updates after the last update_id
61    updates = await bot.get_updates(offset=update_id, timeout=10)
62    for update in updates:
63        next_update_id = update.update_id + 1
64
65        # your bot can receive updates without messages
66        # and not all messages contain text
67        if update.message and update.message.text:
68            # Reply to the message
69            logger.info("Found message %s!", update.message.text)
70            await update.message.reply_text(update.message.text)
71        return next_update_id
72    return update_id
73
74
75if __name__ == "__main__":
76    with contextlib.suppress(KeyboardInterrupt):  # Ignore exception when Ctrl-C is pressed
77        asyncio.run(main())