all repos — gif-escarbot @ 2ff3f843b8dc2f033f84613e7da3630e2e43a627

Earthbound Café's custom delivery bot with other cool utilities built-in.

code refactor, add links replacer
Marco Andronaco andronacomarco@gmail.com
Thu, 24 Aug 2023 02:46:48 +0200
commit

2ff3f843b8dc2f033f84613e7da3630e2e43a627

parent

b8f9ef8f2d16b24a2bfad141bd18d257a3be5a20

7 files changed, 119 insertions(+), 43 deletions(-)

jump to
M .gitignore.gitignore

@@ -1,2 +1,3 @@

.env venv +__pycache__
A .vscode/launch.json

@@ -0,0 +1,16 @@

+{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Python: Bot", + "type": "python", + "request": "launch", + "program": "main.py", + "console": "integratedTerminal", + "justMyCode": true + } + ] +}
A Config.py

@@ -0,0 +1,23 @@

+import logging +from os import getenv +from dotenv import load_dotenv +load_dotenv() +logger = logging.getLogger(__name__) + +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) +logging.getLogger("httpx").setLevel(logging.WARNING) + +def config_error(): + logger.error("Please create and fill the .env file.") + exit(1) + +try: + TOKEN = str(getenv("token")) + GROUP_ID = int(getenv("group_id")) + CHANNEL_ID = int(getenv("channel_id")) + ADMIN_ID = int(getenv("admin_id")) +except TypeError: + config_error() + +if '' in [TOKEN, GROUP_ID, CHANNEL_ID, ADMIN_ID]: + config_error()
A Forwarder.py

@@ -0,0 +1,21 @@

+from telegram import Update +from Config import CHANNEL_ID, GROUP_ID, ADMIN_ID +import logging +logger = logging.getLogger(__name__) + +async def forward(update: Update, _): + if not update.effective_chat.id == CHANNEL_ID: + return logger.info("Ignoring message since it did not come from the correct chat_id.") + + if update.channel_post is None: + return logger.warn("Got an invalid message from the correct chat_id.") + + await update.channel_post.forward(GROUP_ID) + return logger.info("Forwarded a message.") + +async def admin_forward(update: Update, _): + try: + await update.message.forward(ADMIN_ID) + return logger.info(f"Forwarded this message to admin: { update.message.text }") + except: + return logger.error(f"Couldn't forward this update to admin: { update }")
A Replacer.py

@@ -0,0 +1,50 @@

+from telegram import Update +import logging, re +logger = logging.getLogger(__name__) + +re_flags = re.I | re.M + +replacers = [ + { + "regex": re.compile(r"(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([\w\-_]+)\&?", re_flags), + "becomes": "https://y.outube.duckdns.org/{}" + }, + { + "regex": re.compile(r"(?:https?:\/\/)?(?:www\.)?twitter\.com\/(?:#!\/)?(.*)\/status(?:es)?\/([^\/\?\s]+)", re_flags), + "becomes": "https://fxtwitter.com/{}/status/{}" + }, +] + +link_message = "[.]({})" + +def format_template(template: str, regex_result) -> str: + result_type = type(regex_result) + if result_type is str: + return template.format(regex_result) + elif result_type is tuple or result_type is list: + return template.format(*regex_result) + elif result_type is dict: + return template.format(**regex_result) + else: + return "" + +def parse_text(message: str) -> list: + output = [] + for site in replacers: + regex = site["regex"] + res = regex.findall(message) + for r in res: + link = format_template(site["becomes"], r) + output.append(link) + logger.info(output) + return output + +async def replace(update: Update, _) -> None: + try: + links = parse_text(update.message.text) + except TypeError: + links = parse_text(update.message.caption) + + for link in links: + message = link_message.format(link) + await update.message.reply_text(message, parse_mode="markdown")
M main.pymain.py

@@ -1,47 +1,12 @@

from telegram.ext import MessageHandler, ApplicationBuilder, filters from telegram import Update -from dotenv import load_dotenv -from os import getenv -import logging - -async def forward(update: Update, _): - if not update.effective_chat.id == CHANNEL_ID: - return logger.info("Ignoring message since it did not come from the correct chat_id.") - - if update.channel_post is None: - return logger.warn("Got an invalid message from the correct chat_id.") - - await update.channel_post.forward(GROUP_ID) - return logger.info("Forwarded a message.") - -async def admin_forward(update: Update, _): - try: - await update.message.forward(ADMIN_ID) - return logger.info(f"Forwarded this message to admin: {update.message.text}") - except: - return logger.error(f"Couldn't forward this update to admin: {update}") - -def config_error(): - logger.error("Please create and fill the .env file.") - exit(1) +from Config import TOKEN +from Replacer import replace +from Forwarder import forward, admin_forward if __name__ == "__main__": - logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) - logger = logging.getLogger(__name__) - load_dotenv() - - try: - TOKEN = str(getenv("token")) - GROUP_ID = int(getenv("group_id")) - CHANNEL_ID = int(getenv("channel_id")) - ADMIN_ID = int(getenv("admin_id")) - except TypeError: - config_error() - - if '' in [TOKEN, GROUP_ID, CHANNEL_ID, ADMIN_ID]: - config_error() - application = ApplicationBuilder().token(TOKEN).build() application.add_handler(MessageHandler(filters.ChatType.CHANNEL, forward)) application.add_handler(MessageHandler(filters.ChatType.PRIVATE, admin_forward)) - application.run_polling() + application.add_handler(MessageHandler(filters.CHAT & ~filters.COMMAND, replace)) + application.run_polling(allowed_updates=Update.MESSAGE)
M poetry.lockpoetry.lock

@@ -22,13 +22,13 @@ trio = ["trio (<0.22)"]

[[package]] name = "certifi" -version = "2023.5.7" +version = "2023.7.22" description = "Python package for providing Mozilla's CA Bundle." optional = false python-versions = ">=3.6" files = [ - {file = "certifi-2023.5.7-py3-none-any.whl", hash = "sha256:c6c2e98f5c7869efca1f8916fed228dd91539f9f1b444c314c06eef02980c716"}, - {file = "certifi-2023.5.7.tar.gz", hash = "sha256:0f0d56dc5a6ad56fd4ba36484d6cc34451e1c6548c61daad8c320169f91eddc7"}, + {file = "certifi-2023.7.22-py3-none-any.whl", hash = "sha256:92d6037539857d8206b8f6ae472e8b77db8058fec5937a1ef3f54304089edbb9"}, + {file = "certifi-2023.7.22.tar.gz", hash = "sha256:539cc1d13202e33ca466e88b2807e29f4c13049d6d87031a3c110744495cb082"}, ] [[package]]