Stuckach/main.py

57 lines
2.2 KiB
Python

import logging
import os
import requests
from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import Application, CommandHandler, ContextTypes
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
async def ping_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
ready_message = await context.bot.send_message(chat_id=update.effective_chat.id,
text="*️⃣ Requesting...")
try:
resp = requests.post(os.getenv("REQUEST_URL"), headers={'User-Agent': 'Custom'})
message = f"✅ Server responded with HTTP status code *{resp.status_code}*."
except Exception as e:
message = "❌ Caught exception. Server is probably *offline*."
dev_message = (f"Caught exception @ *{update.effective_chat.effective_name}* "
f"(`{update.effective_chat.id}`)\n"
f"```\n{e}```")
await context.bot.send_message(chat_id=os.getenv("DEVELOPER_ID"),
text=dev_message,
parse_mode=ParseMode.MARKDOWN)
await context.bot.edit_message_text(text=str(message),
chat_id=ready_message.chat.id,
message_id=ready_message.message_id,
parse_mode=ParseMode.MARKDOWN)
def main() -> None:
envs_not_set = False
envs = ['BOT_TOKEN', 'REQUEST_URL', 'DEVELOPER_ID']
for env in envs:
if os.getenv(env) is None:
envs_not_set = True
print(f"{env} is not set.")
if envs_not_set: exit(1)
# Create the Application and pass it your bot's token.
application = Application.builder().token(os.getenv("BOT_TOKEN")).build()
application.add_handler(CommandHandler("ping", ping_command))
# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()