import logging
from telegram import Update
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
logger = logging.getLogger(__name__)
def _help_msg():
return """Respondo a los siguientes comandos:
/ping - Pong.
/who - Información sobre ti y tu mensaje (para debugging).
"""
class PingBot(object):
def __init__(self, bot_token: str, bot_name: str) -> None:
self.token = bot_token
self.name = bot_name
# Create the Application and pass it your bot's token.
application = (
Application.builder()
.token(bot_token)
.concurrent_updates(True)
.build()
)
# on different commands - answer in Telegram
application.add_handler(CommandHandler("start", PingBot.start))
application.add_handler(CommandHandler("help", PingBot.help))
application.add_handler(CommandHandler("stop", PingBot.stop))
application.add_handler(CommandHandler("ping", PingBot.ping))
application.add_handler(CommandHandler("whoami", self.who))
application.add_handler(
MessageHandler(filters.TEXT & ~filters.COMMAND, PingBot.echo)
)
self.app = application
@staticmethod
async def start(
update: Update, _context: ContextTypes.DEFAULT_TYPE
) -> None:
"""Welcome message to a new user."""
assert update.message is not None
await update.message.reply_text("Hi! I'm a simple utilities bot.")
@staticmethod
async def help(update: Update, _context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /help is issued."""
assert update.message is not None
await update.message.reply_text(_help_msg())
@staticmethod
async def echo(update: Update, _context: ContextTypes.DEFAULT_TYPE) -> None:
"""Repeats any message that is not a command."""
assert update.message is not None
await update.message.reply_text(update.message.text or "")
@staticmethod
async def ping(update: Update, _context: ContextTypes.DEFAULT_TYPE) -> None:
"""Pongs back."""
assert update.message is not None
await update.message.reply_text("Pong!")
@staticmethod
async def stop(update: Update, _context: ContextTypes.DEFAULT_TYPE) -> None:
user = update.effective_user
assert user is not None
logger.warning(
"I got blocked by user {} [{}]".format(user.username, user.id)
)
async def who(
self, update: Update, _context: ContextTypes.DEFAULT_TYPE
) -> None:
msg = update.message
user = update.effective_user
chat = update.effective_chat
assert msg is not None
assert user is not None
assert chat is not None
name = chat.effective_name
date = msg.date.astimezone()
answer = (
"You're {name}, with username {username}"
" and id {uid}.\nWe are on a ctype "
"'{ctype}' chat named {cname}, with chat id "
"{cid}, and the time right now is "
"{tstamp}."
).format(
name=user.full_name,
username=user.username,
uid=user.id,
cname=name,
cid=chat.id,
ctype=chat.type,
tstamp=str(date),
)
await msg.reply_html(answer)
async def start_app(self) -> None:
"""Starts the bot app."""
await self.app.initialize()
await self.app.start()
await self.app.updater.start_polling(allowed_updates=Update.ALL_TYPES)
logger.info("%s started up!", self.name)
# await self.notify_admins(f"Telegram Bot started up!\n{whitelist_str}")
async def stop_app(self) -> None:
"""Stops the bot app."""
# await self.notify_admins("Shutting down!")
await self.app.updater.stop()
await self.app.stop()
await self.app.shutdown()
logger.info("%s stopped", self.name)