Example #1
0
 def start(self, bot: Bot, update: Update) -> None:
     if update.message.chat_id not in parse_list(
             config["CHATS"]["main_chats"]):
         from_id = update.message.from_user.id
         from_username = update.message.from_user.username
         name = f"user:{from_id}"
         if from_username is not None:
             rdb.hsetnx(name, "username", from_username)
         if rdb.hget(name, "allowed") == "true":
             update.message.reply_text(config["STRINGS"]["user_took_quiz"])
         else:
             keyboard = [[InlineKeyboardButton(
                     config["STRINGS"]["ready"],
                     callback_data="ready")]]
             reply_markup = InlineKeyboardMarkup(keyboard)
             update.message.reply_text(
                 config["STRINGS"]["start_message"].format(
                     username=from_username or "fellow pythonist",
                     start=config["COMMANDS"]["start"],
                     correct_answers=config["GENERAL"]["correct_answers"],
                     questions_count=config["GENERAL"]["questions_count"]),
                 parse_mode="Markdown",
                 reply_markup=reply_markup)
     else:
         if config["GENERAL"]["send_start_no"] == "true":
             update.message.reply_text(config["STRINGS"]["no"])
         if config["GENERAL"]["delete_commands"] == "true":
             bot.delete_message(chat_id=update.message.chat.id,
                                message_id=update.message.message_id)
Example #2
0
 def remove(self, bot: Bot, update: Update) -> None:
     if is_admin(bot, update, update.message.from_user.id):
         pass
     else:
         if config["GENERAL"]["delete_commands"] == "true":
             bot.delete_message(chat_id=update.message.chat.id,
                                message_id=update.message.message_id)
Example #3
0
 def lban(self, bot: Bot, update: Update) -> None:
     from_id: int = update.message.from_user.id
     message: str = update.message.text
     if is_admin(bot, update, from_id) and len(message.split()) >= 2:
         ids_to_ban: dict = {}
         final_message = "<b>Banning log:</b>\n"
         if update.message.reply_to_message:
             reply_id = update.message.reply_to_message.from_user.id
             ids_to_ban[reply_id] = update.message.reply_to_message.\
                 from_user.username
         else:
             entities = update.message.parse_entities()
             for entity in entities:
                 mention = message[entity.offset:
                                   entity.offset + entity.length]
                 if entity.type == "mention":
                     user_id = rdb.get(f"username:{mention[1:]}")
                     if user_id != 0:
                         ids_to_ban[user_id] = mention
                 elif entity.type == "phone_number":
                     try:
                         from_user_id = bot.getChatMember(
                             chat_id=update.message.chat.id,
                             user_id=mention)
                         ids_to_ban[from_user_id.user.id] = \
                             from_user_id.user.first_name
                     except error.BadRequest:
                         continue
                 elif entity.type == "text_mention":
                     ids_to_ban[entity.user.id] = entity.user.first_name
         for usr in ids_to_ban:
             status: str = ""
             log_msg = f"<code>{ids_to_ban[usr]} {'.'*5} {status}</code>\n"
             try:
                 bot.kickChatMember(
                     chat_id=update.message.chat_id,
                     user_id=usr)
                 final_message += log_msg.format(status="OK")
             except error.BadRequest:
                 final_message += log_msg.format(status="FAIL")
         bot.sendMessage(
             chat_id=update.message.chat.id,
             text=final_message,
             parse_mode="HTML")
     else:
         if config["GENERAL"]["delete_commands"] == "true":
             bot.delete_message(chat_id=update.message.chat.id,
                                message_id=update.message.message_id)
Example #4
0
 def test(self, bot: Bot, update: Update) -> None:
     if is_admin(bot, update, update.message.from_user.id):
         command = update.message.text.split()
         start_index: int = 0
         end_index: int = -1
         syntax = command[1].split("-") if len(command) == 2 else None
         if is_digit(syntax[0]) and is_digit(syntax[1]):
             start_index = int(syntax[0])
             end_index = int(syntax[1])
         for question in quizzes["quizzes"][start_index:end_index]:
             text = f'<code>(ID: {quizzes["quizzes"].index(question)})' \
                 f'</code>\n{question["question"]}\n'
             text += "\n".join(question["options"])
             text += "\nAnswer: " + str(question["answer"])
             update.message.reply_text(text, parse_mode="HTML")
             time.sleep(int(config["GENERAL"]["test_delay"]))
     else:
         if config["GENERAL"]["delete_commands"] == "true":
             bot.delete_message(chat_id=update.message.chat.id,
                                message_id=update.message.message_id)
Example #5
0
 def extra(self, bot: Bot, update: Update) -> None:
     user_id: int = update.message.from_user.id
     if is_admin(bot, update, user_id):
         text: str = update.message.text
         value_pattern = re.compile("\\[\\s*.*\\s*\\]")
         key_pattern = re.compile("#[_A-z0-9]*")
         value_match = re.findall(value_pattern, text)
         key_match = re.findall(key_pattern, text)
         value = value_match[0] if len(value_match) >= 1 else None
         key = key_match[0] if len(key_match) >= 1 else None
         if key and value:
             # TODO: add functionality
             pass
         else:
             update.message.reply_text(
                 text=config["STRINGS"]["failed_match"],
                 parse_mode="Markdown")
     else:
         if config["GENERAL"]["delete_commands"] == "true":
             bot.delete_message(chat_id=update.message.chat.id,
                                message_id=update.message.message_id)
Example #6
0
 def check_url(self):
     """
     检查是否有url,如果有,是否满足规则
     :param msg:
     :return:
     """
     allurl = re.finditer(r'((https|http):\/\/)?((\w)*\.){1,2}(com|cn|net|io|pro|top|wang|pub|xin|xyz)', self.text)
     if allurl:
         for match in allurl:
             match_obj = re.match(r'^((https|http):\/\/)?(\w)*\.?yunex.io', "".join(match.group()))
             # 遍历所匹配到的url
             if match_obj is not None:
                 # 如果匹配到的是我们官网的域名,continue
                 continue
             else:
                 # 如果匹配到其他的域名,删除该消息
                 bot.delete_message(self.chat.id, self.message_id)
                 bot.restrict_chat_member(str(self.chat.id), self.from_user.id, int(time.time()) + 7200)
                 return
     else:
         # 未匹配到url,不做任何操作
         pass
Example #7
0
    def __deleteLastMessages(self, context: CallbackContext,
                             update: Update) -> None:

        if c.CHAT_ID not in context.user_data:
            context.user_data[c.CHAT_ID] = update.message.chat_id
            # delete user's last message
            Bot.delete_message(context.bot,
                               chat_id=update.message.chat_id,
                               message_id=update.message.message_id)
        else:
            # delete bot's last message
            Bot.delete_message(context.bot,
                               chat_id=context.user_data[c.CHAT_ID],
                               message_id=context.user_data[c.MSG_ID])
            try:
                # delete user's last message, if present
                Bot.delete_message(context.bot,
                                   chat_id=update.message.chat_id,
                                   message_id=update.message.message_id)
            except:
                pass
Example #8
0
class Telegram:
    def __init__(self, bot_token, proxy=None):
        if proxy:
            self.__bot = Bot(bot_token, request=Request(proxy_url=proxy))
        else:
            self.__bot = Bot(bot_token)

    def __get_keyboard(self, buttons):
        keyboard = []
        if "link" in buttons:
            keyboard.append([
                InlineKeyboardButton("Artikel lesen ↗️", url=buttons["link"])
            ])
        if "magazine" in buttons:
            keyboard.append([
                InlineKeyboardButton("Ausgabe lesen ↗️",
                                     url=buttons["magazine"])
            ])
        if "ad" in buttons:
            keyboard.append([
                InlineKeyboardButton("DerNewsChannel ↗️",
                                     url="https://t.me/DerNewsChannel")
            ])
        if "more" in buttons and len(keyboard):
            keyboard[0].insert(
                0,
                InlineKeyboardButton("Mehr {}".format(buttons["more"][0]),
                                     url=buttons["more"][1]),
            )
        return InlineKeyboardMarkup(keyboard)

    def send_img(self, msg, channel_id, keyboard, img):
        try:
            msg_id = self.__bot.send_photo(
                caption=msg,
                photo=img if img[:4] == "http" else open(img, "rb"),
                chat_id=channel_id,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=self.__get_keyboard(keyboard),
                timeout=60,
            )["message_id"]
        except Exception as e:
            logging.exception(e)
            msg_id = 0
        return msg_id

    def send(
        self,
        msg,
        channel_id,
        buttons,
        disable_notification=False,
        disable_preview=False,
    ):
        msg_id = 0
        try:
            msg_id = self.__bot.sendMessage(
                text=msg,
                chat_id=channel_id,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=self.__get_keyboard(buttons),
                timeout=60,
                disable_notification=disable_notification,
                disable_web_page_preview=disable_preview,
            )["message_id"]
        except TimedOut:
            logging.error(
                "Sending news timed out - probably too many messages")
        except RetryAfter as e:
            logging.error(e)
        except BadRequest as e:
            if "Can't parse entities" in str(e):
                logging.error(str(e) + msg)
        except Exception as e:
            logging.exception(e)
        return msg_id

    def edit(
        self,
        i,
        msg,
        channel_id,
        buttons,
        disable_notification=False,
        disable_preview=False,
    ):
        counter = 0
        while True:
            try:
                print(i)
                i += 1
                self.__bot.editMessageText(
                    message_id=i,
                    text=msg,
                    chat_id=channel_id,
                    parse_mode=ParseMode.MARKDOWN,
                    reply_markup=self.__get_keyboard(buttons),
                    disable_notification=disable_notification,
                    disable_web_page_preview=disable_preview,
                )
            except Exception as e:
                if "Message is not modified" in str(e):
                    return i
                if "Message to edit not found" == str(e):
                    counter += 1
                    if counter < 100000:
                        continue
                    return self.send(
                        msg,
                        channel_id,
                        buttons,
                        disable_notification=disable_notification,
                        disable_preview=disable_preview,
                    )
                if "Timed out" == str(e):
                    time.sleep(5)
                    i -= 1
                continue
            return i

    def delete(self, msg_id, channel_id):
        try:
            self.__bot.delete_message(channel_id, msg_id, timeout=60)
            time.sleep(3)
        except Exception as e:
            if "Message identifier is not specified" in str(e):
                pass
            elif "Message to delete not found" in str(e):
                pass
            elif "Message can't be deleted" in str(e):
                pass
            else:
                logging.exception(e)

    def unpin(self, channel_id):
        try:
            self.__bot.unpin_chat_message(channel_id, timeout=60)
        except BadRequest:
            pass

    def pin(self, channel_id, msg_id):
        try:
            self.__bot.pinChatMessage(
                chat_id=channel_id,
                message_id=msg_id,
                disable_notification=True,
                timeout=60,
            )
        except BadRequest:
            logging.error("Can't pin message in the private chat")
        except Exception as e:
            logging.exception(e)

    def get_chat(self, channel_id):
        return self.__bot.get_chat(channel_id, timeout=60)

    def get_invite_link(self, channel_id):
        return self.__bot.export_chat_invite_link(channel_id, timeout=60)

    def set_title(self, channel_id, title):
        self.__bot.set_chat_title(channel_id, title, timeout=60)

    def set_description(self, channel_id, description):
        try:
            self.__bot.set_chat_description(channel_id,
                                            description,
                                            timeout=60)
        except BadRequest as e:
            if "Chat description is not modified" not in str(e):
                logging.exception(e)

    def set_photo(self, channel_id, photo):
        img = open("{}/img/{}".format(os.path.dirname(sys.argv[0]), photo),
                   "rb")
        self.__bot.set_chat_photo(channel_id, img, timeout=60)

    def send_exception(self, error_channel=None, name="", article="", link=""):
        msg = ""
        if name:
            msg += "*{}*\n".format(name)
        if article and link:
            msg += "[{}]({})\n".format(article, link)
        try:
            tb = traceback.format_exc()
            if len(tb) > 3400:
                tb = tb[-3400:]
            msg += "\n`{}`".format(tb)
            self.send(msg, error_channel, [], disable_preview=True)
        except Exception:
            pass

    def get_chat_infos(self, channel_id):
        chat = self.get_chat(channel_id)
        if not chat["username"]:
            if not chat["invite_link"]:
                self.get_invite_link(channel_id)
                chat = self.get_chat(channel_id)
            name = chat["invite_link"]
        else:
            name = chat["username"]
        return name