示例#1
0
def dota_news(message):
    if intime(message):
        cid = getCID(message)
        content = getContent(message)
        url = "http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=570&count=1&maxlength=300&format=json"
        request = requests.get(url)
        data = request.json()
        if content != "?":
            if request.status_code == 200:
                title = data['appnews']['newsitems'][0]['title']
                content = data['appnews']['newsitems'][0]['contents']
                content_nice = content.replace(" - ", "\n - ")
                content_nice = content_nice.replace("*", "\n*")
                content_nice = parser.unescape(content_nice)
                url = data['appnews']['newsitems'][0]['url']
                bot.send_message(
                    cid,
                    u'*{title}*```> \n{content_nice}\n[...]\n```'.format(title=title, content_nice=content_nice)
                    + u'[More info here]({url})'.format(url=url),
                    parse_mode="Markdown",
                    disable_web_page_preview=True)
            else:
                bot.reply_to(
                    message,
                    "`There has been an error, the number {error} to be specific.`"
                        .format(error=request.status_code),
                    parse_mode="Markdown")
        else:
            bot.reply_to(
                message,
                "`Send this command alone and I will show you the last Steam News for Dota2 entry`",
                parse_mode="Markdown")
示例#2
0
def welcome(message):
    new_members_names = []
    # By default assumes that the new user has joined for the first time
    first_joined = True

    # Gets the information about the current chat members in data
    with shelve.open(config.data_name, 'c', writeback=True) as data:
        data['members'] = {} if not data.get('members') else data['members']
        # Checks every new member
        # NOTE, you can invite multiple users at once
        for member in message.new_chat_members:
            # If new member is bot, skips
            if member.is_bot:
                continue

            # If new member has joined for the first time
            # adds him/her to the database
            if not member.id in data['members']:
                data['members'][member.id] = ' '.join(
                    get_user(member).split(' ')[1:])
                logger.info('User {} has joined the chat for the first time and '\
                            'has been successfully added to the database'.format(get_user(member)))
            # Else, sets first_joined flag to False
            else:
                first_joined = False
                logger.info('User {} has rejoined the chat'.format(
                    get_user(member)))
            new_members_names.append(member.first_name)
    # Welcomes every new member
    if new_members_names:
        welcoming_msg = '{0}, {1}!\nPlease consider the chat rules and enjoy your stay.'.format(random.choice(constants.welcome_list),\
                                    ', '.join(new_members_names)) if first_joined else '{0}, {1}.'.format(random.choice(constants.welcomeback_list),\
                                    ', '.join(new_members_names))
        bot.reply_to(message, welcoming_msg)
示例#3
0
def random_message(message, string_list, mode):
    '''
    Sands random massage and sticker

    Parameters
        ----------
        message : str
            message from  chat
        string_list : str
            Json list with texts
        mode : type
            SEND_MESSAGE, REPLY_MESSAGE
    '''

    strings_num = len(string_list['strings'])
    r_number = randrange(0, strings_num, 1)

    if string_list['strings'] and string_list['strings'][r_number]:
        if mode is SEND_MESSAGE:
            bot.send_message(message.chat.id,
                             string_list['strings'][r_number],
                             parse_mode='Markdown')
        elif mode is REPLY_MESSAGE:
            bot.reply_to(message,
                         string_list['strings'][r_number],
                         parse_mode='Markdown')
    if string_list['stickers'] and string_list['stickers'][r_number]:
        bot.send_sticker(message.chat.id, string_list['stickers'][r_number])
        def wrap(message, **_):
            args = message.text.split(' ')
            if len(args) > 1:
                del args[0]
            else:
                args = []

            res_kwargs = {}
            for i, k in enumerate(kwargs.keys()):
                validator, default, required = kwargs[k]
                if i < len(args):
                    value = args[i]
                else:
                    if required:
                        return bot.reply_to(
                            message,
                            f'Required field "{k}" of {validator.__name__} '
                            'type')
                    value = default

                try:
                    res_kwargs[k] = validator(value)
                except ValueError as e:
                    return bot.reply_to(
                        message, f'Invalid type for "{k}" field: {str(e)} ')

            return fun(message, **res_kwargs)
示例#5
0
def get_admins(message):
    # Gets all human administrators of a chat
    admins_objects = [
        admin for admin in bot.get_chat_administrators(config.chat_id)
        if not admin.user.is_bot
    ]
    # Gets every administrator's id, appends the default admins' ids
    admins_ids = [ad.user.id
                  for ad in admins_objects] + [*config.admins_default]

    # Writes all admins' ids and information to data
    # Removes obsolete admins
    # Sends a message with the output
    with shelve.open(config.data_name, 'c', writeback=True) as data:
        data['admins'] = config.admins_default if not data.get(
            'admins') else data['admins']

        for admin in admins_objects:
            admin_id = admin.user.id
            admin_data = '@' + admin.user.username if admin.user.username else admin.user.first_name
            if admin_id not in data['admins']:
                data['admins'][admin_id] = admin_data

        for admin_id in list(data['admins']):
            if admin_id not in admins_ids:
                del data['admins'][admin_id]

        bot.reply_to(
            message,
            'List of bot\'s admins:\n{}'.format(print_dict(data['admins'])))
示例#6
0
def update_bot(message):
    if not hasattr(update_bot, "check_sure"):
        update_bot.check_sure = True
        bot.reply_to(message, "Are you sure?")
        return
    bot.reply_to(message, "Ух, ухожу на обновление...")
    os.execl('/bin/bash', 'bash', 'bot_update.sh')
示例#7
0
def get_info(message):
    gitUrl = "https://github.com/zachkont/dotaUpdatesBot"
    bot.reply_to(message,
                    u'The main use of this bot is to notify you whenever a Dota update gets released.\n'
                    + u'Visit the [GitHub page]({gitUrl})'.format(gitUrl=gitUrl)
                    + u' for more information on what you can do or how to contribute!',
                    parse_mode="Markdown",
                    disable_web_page_preview=True)
示例#8
0
def kill_bot(message):
    if not hasattr(kill_bot, "check_sure"):
        kill_bot.check_sure = True
        bot.reply_to(message, "Are you sure?")
        return
    value_to_file(config.file_location['bot_killed'], 1)
    bot.reply_to(message, "Ух, ухожу на отдых...")
    os._exit(0)
示例#9
0
def life_question(message):
    '''
    LOL
    '''

    logger.info("[LIFE] command by {:s}, Username @{:s} | '{:s}'".format(
        message.from_user.first_name, (message.from_user.username or "NONE"),
        message.text))
    bot.reply_to(message, "*42*", parse_mode='Markdown')
示例#10
0
def start_msg(message):
    if not validate_command(message, check_isprivate=True, check_isadmin=True):
        return

    start_text = ("Вы действительно админ чата {}.\n"
                  "Значит я вам сюда буду пересылать пользовальские репорты "
                  "и подозрительные сообщения.".format(config.chat_name))
    bot.reply_to(message, start_text)
    logger.info("Admin {} has initiated a chat with the bot".format(
        get_user(message.from_user)))
示例#11
0
def get_user_id_message(message):
    if message.forward_from:
        return
    logger.info("/getuserid command by {:s}, Username @{:s}".format(
        message.from_user.first_name, (message.from_user.username or "NONE")))

    bot.reply_to(message,
                 ru_strings.GET_ID_MESSAGE['strings'][0].format(
                     message.from_user.id),
                 parse_mode='Markdown')
示例#12
0
def update_admin_list(message):
    if not validate_command(message, check_isprivate=True, check_isadmin=True):
        return

    config.admin_ids = get_admins(config.chat_id)
    admins = ",\n".join([str(admin) for admin in config.admin_ids])
    update_text = "Список администратов успешно обновлён:\n{}".format(admins)
    bot.reply_to(message, update_text)
    logger.info("Admin {} has updated the admin list".format(
        get_user(message.from_user)))
示例#13
0
def paste(message):
    source = message.reply_to_message
    source_text = source.text or source.caption
    new_paste = make_paste(source_text, source.from_user.first_name)
    if not new_paste:
        return
    bot.reply_to(source, text=new_paste, disable_web_page_preview=True)
    bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)
    logger.info(
        "User {0} has requested a paste version of a message {1}".format(
            get_user(message.from_user), message.reply_to_message.message_id))
示例#14
0
def get_help(message):
    gitUrl = "https://github.com/zachkont/dotaUpdatesBot"
    redditUrl = "https://www.reddit.com/message/compose/?to=karaflix"
    bot.reply_to(message,
                    u'Did you find a bug or have any questions?\n'
                    + u'Visit the [GitHub page]({gitUrl})'.format(gitUrl=gitUrl)
                    + u' for more information or contact'
                    + u' [/u/karaflix]({redditUrl})'.format(redditUrl=redditUrl)
                    + u' on reddit!',
                    parse_mode="Markdown",
                    disable_web_page_preview=True)
示例#15
0
def send_to_admin(message, text, admins, is_forward):
    text = text.format(get_user(message.reply_to_message.forward_from)) if is_forward else \
           text.format(get_user(message.reply_to_message.from_user))
    try:
        bot.send_message(message.from_user.id, text)
        logger.info(text.format(get_user(message.reply_to_message.from_user)))
    except ApiException as e:
        if str(e.result) == r'<Response [403]>':
            reply_msg = text + '\nI can\'t contact you. Please start a chat with me.'
            bot.reply_to(message, reply_msg)
            logger.error('Admin {} couldn\'t be reached'.format(
                admins[message.from_user.id]))
示例#16
0
def photo_receive(message):
    '''
    Recognizes photos with the comment "персик"
    Ban for NSFW
    '''

    file_id = message.photo[len(message.photo) - 1].file_id

    if message.caption and message.forward_from is None:
        if re.match('(?i)(\W|^).*?!п[eеэ][pр][cс](и|ч[eеи]к).*?(\W|$)',
                    message.caption):
            bot.reply_to(message,
                         "".join([
                             message.from_user.first_name,
                             picturedetect.reply_get_concept_msg(file_id)
                         ]),
                         parse_mode='Markdown')

    logger.info("Photo by Username @{:s} | ID {:s}".format(
        (message.from_user.username or "NONE"), file_id))

    try:
        os.makedirs("./photos")
    except FileExistsError:
        pass

    file_patch = './photos/{:s}.jpg'.format(file_id)
    _file = Path(file_patch)
    if _file.is_file() is not True:
        file_info = bot.get_file(file_id)
        file_patch = utils.file_download(file_info, './photos/')

    if file_patch is None:
        logger.error("File download error!'")

        bot.reply_to(message,
                     ru_strings.SOME_ERROR_MESSAGE['strings'],
                     parse_mode='Markdown')
        bot.send_sticker(message.chat.id,
                         ru_strings.SOME_ERROR_MESSAGE['stickers'][0])

        return

    if not allow_nsfw:
        if picturedetect.nsfw_test(file_patch, 0.75):
            bot.delete_message(message.chat.id, message.message_id)

            bot.send_message(
                message.chat.id,
                "*{} уходит в бан на {} {}! Причина: NSFW*".format(
                    message.from_user.first_name, 2, 'мин.'),
                parse_mode='Markdown')
            ban_user(message.chat.id, message.from_user.id, 2 * 60)
示例#17
0
def kek(message):
    your_kek = ''

    # Tries to gather data from the text files
    try:
        with open(kek_text_name, 'r', encoding='utf-8') as kek_text, open(
                kek_ids_name, 'r', encoding='utf-8') as kek_ids:
            type_of_kek = random.randint(1, 4)
            # 25% chance for a special kek
            if type_of_kek == 1:
                while your_kek in ['', ' ', '\n', ' \n']:
                    your_kek = random.choice(kek_ids.readlines()).strip()
                kek_type = first(
                    ['<audio>', '<photo>', '<sticker>', '<voice>'],
                    key=lambda x: x in your_kek)
                file_id = your_kek.split(kek_type)[1].strip()

                # NOTE, media ids are unique for each bot
                if kek_type == '<audio>':
                    bot.send_audio(message.chat.id,
                                   file_id,
                                   reply_to_message_id=message.message_id)
                elif kek_type == '<photo>':
                    bot.send_photo(message.chat.id,
                                   file_id,
                                   reply_to_message_id=message.message_id)
                elif kek_type == '<sticker>':
                    bot.send_sticker(message.chat.id,
                                     file_id,
                                     reply_to_message_id=message.message_id)
                elif kek_type == '<voice>':
                    bot.send_voice(message.chat.id,
                                   file_id,
                                   reply_to_message_id=message.message_id)
            else:
                while your_kek in ['', ' ', '\n', ' \n']:
                    your_kek = random.choice(kek_text.readlines()).strip()
                bot.reply_to(message, str(your_kek).replace('<br>', '\n'))
            logger.info('User {0} got this kek: {1}'.format(
                get_user(message.from_user), your_kek))
    # If the text files are empty or non-existent
    except (OSError, IOError) as e:
        bot.reply_to(
            message,
            'Can\'t access the kek files. Please, make sure they are in \'data\' directory and they are non-empty.'
        )
        logger.info(e)
    except Exception as e:
        logger.exception(e)
示例#18
0
def document_to_paste(message):
    document = message.document
    file_info = bot.get_file(document.file_id)
    try:
        file_content = bot.download_file(file_info.file_path).decode()
    except UnicodeDecodeError:
        logger.info("Can't decode file content")
        return
    new_paste = make_paste(file_content, message.from_user.first_name,
                           document.file_name)
    if not new_paste:
        return
    bot.reply_to(message, text=new_paste)
    logger.info(
        "Successfully created a paste of a document from message {}".format(
            message.message_id))
示例#19
0
def justify(message):
    source = message.reply_to_message

    if not validate_command(message, check_isadmin=True):
        return

    if perfect_justice():
        bot.reply_to(source, text="Bang! РО на день")
        tomorrow = datetime.date.today() + datetime.timedelta(1)
        unix_time = tomorrow.strftime("%s")
        bot.restrict_chat_member(
            chat_id=config.chat_id, user_id=source.from_user.id, until_date=unix_time
        )
    else:
        bot.reply_to(source, text="Lucky one")

    bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)
示例#20
0
def end_subscription(message):
    uid = str(message.from_user.id)
    cid = str(message.chat.id)

    if message.chat.type == 'private':
        if uid in loadjson("userlist"):
            deljson(uid, "userlist")
            bot.send_message(uid, 'You have been removed from the subscription list', parse_mode="Markdown")
        else:
            bot.send_message(uid, 'You can\'t unsubscribe without subscribing first dummy!', parse_mode="Markdown")
    elif message.chat.type == 'group' or message.chat.type == 'supergroup':
        if cid in loadjson("grouplist"):
            bot.reply_to(message, 'Oh, no more updates? Okay...', parse_mode="Markdown")
            gid = str(message.chat.id)
            deljson(gid, "grouplist")
        else:
            bot.send_message(cid, 'Not subscibed yet', parse_mode="Markdown")
    else:
        pass
示例#21
0
def persik_keyword(message):
    if message.forward_from:
        return
    try:
        logger.info("!Persik command by {:s}, Username @{:s}".format(
            message.from_user.first_name,
            (message.from_user.username or "NONE")))

        if message.reply_to_message and message.reply_to_message.photo:
            file_info = bot.get_file(message.reply_to_message.photo[
                len(message.reply_to_message.photo) - 1].file_id)
            msg = picturedetect.reply_get_concept_msg(file_info.file_id)
            if msg is None:
                bot.reply_to(message,
                             ru_strings.SOME_ERROR_MESSAGE['strings'],
                             parse_mode='Markdown')
                bot.send_sticker(message.chat.id,
                                 ru_strings.SOME_ERROR_MESSAGE['stickers'][0])
                return

            bot.delete_message(message.chat.id, message.message_id)
            bot.reply_to(message.reply_to_message,
                         "".join([message.from_user.first_name, msg]),
                         parse_mode='Markdown')
            return

        if len(message.text) < 10:
            come_here_message(message)
            return

        for template in MESSAGE_TEMPLATES:
            if re.search(template[0], message.text, re.I | re.U):
                template[1](message)
                return

        random_message(message, ru_strings.NA_MESSAGE, REPLY_MESSAGE)

        logger.info("UNKNOWN command by {:s}, Username @{:s}".format(
            message.from_user.first_name,
            (message.from_user.username or "NONE")))
    except Exception as e:
        logger.error("(persik_keyword) Unexpected error: {}".format(e))
示例#22
0
def kek_add(message):
    add_text = ''
    add_id = ''

    # Tries to write new data to either a file with text or a file with ids
    try:
        with open(kek_text_name, 'a+', encoding='utf-8') as kek_text, open(
                kek_ids_name, 'a+', encoding='utf-8') as kek_ids:
            if getattr(message, 'text'):
                add_text = message.text
                kek_text.write('\n' + add_text)
            elif getattr(message, 'sticker'):
                add_id = '<sticker>{}'.format(message.sticker.file_id)
            elif getattr(message, 'audio'):
                add_id = '<audio>{}'.format(message.audio.file_id)
            elif getattr(message, 'voice'):
                add_id = '<voice>{}'.format(message.voice.file_id)
            elif getattr(message, 'photo'):
                add_id = '<photo>{}'.format(message.photo[0].file_id)

            if not (add_text or add_id):
                bot.reply_to(message, 'Sorry, couldn\'t add your kek. Only text, photos, stickers, audio and voice files '\
                                      'are supported by now.')
                logger.info('Couldn\'t add a kek')
                return

            kek_ids.write('\n' + add_id)

            logger.info('Admin {0} added this kek: {1}{2}'.format(
                get_user(message.from_user), add_text, add_id))
    # If the files are nonexistent
    except OSError as e:
        bot.reply_to(
            message,
            'Can\'t access the kek files. Please, make sure that they are in \'data\' directory and they are non-empty.'
        )
        logger.info(e)
    except Exception as e:
        logger.exception(e)
示例#23
0
def start_subscription(message):
    uid = str(message.from_user.id)
    cid = str(message.chat.id)

    if message.chat.type == 'private':
        if uid not in loadjson("userlist"):
            addUser(uid, message.from_user.first_name, "userlist")
            bot.send_message(uid, 'You will now receive updates!', parse_mode="Markdown")
        else:
            bot.send_message(uid, 'halloooooo', parse_mode="Markdown")
    elif message.chat.type == 'group' or message.chat.type == 'supergroup':
        if cid not in loadjson("grouplist"):
            bot.reply_to(
                message,
                'Hello fans, this awesome group is now added and I will keep you guys up to date',
                parse_mode="Markdown")
            gid = str(message.chat.id)
            gname = message.chat.title
            addUser(gid, gname, "grouplist")
        else:
            bot.send_message(cid, 'Hello again fans, your group has already been registered', parse_mode="Markdown")
    else:
        pass
示例#24
0
def smoke_question(message):
    logger.info("[SMOKE] command by {:s}, Username @{:s} | '{:s}'".format(
        message.from_user.first_name, (message.from_user.username or "NONE"),
        message.text))
    bot.reply_to(message, "*Однозначно, дуть!*", parse_mode='Markdown')
示例#25
0
def send_welcome(message):
    bot.reply_to(message, "Howdy, how are you doing?")
示例#26
0
def find_match(message):
    if intime(message):
        cid = getCID(message)
        content = getContent(message)

        match_id = message.text
        match_id = match_id.split()[1]
        try:
            match = api.get_match_details(match_id)

            url = match.url
            request = requests.get(url)
            match_data = request.json()

            if content != "?":
                if request.status_code == 200:
                    hero_list = []
                    if match_data['result']['radiant_win']:
                        title = "Radiant!"
                    else:
                        title = "Dire!"

                    url = "http://www.dotabuff.com/matches/" + match_id

                    radiant_content = ""
                    dire_content = ""
                    for player in match_data['result']['players']:
                        if player['player_slot'] < 100:  # radiant
                            for hero in heroes_list:
                                if hero['id'] == player['hero_id']:
                                    hero_list.append(hero['localized_name'])
                                    radiant_content = (radiant_content +
                                        hero['localized_name'] + " " +
                                        str(player['kills']) + "/" +
                                        str(player['deaths']) + "/" +
                                        str(player['assists']) + '\n')
                        else:  # dire
                            for hero in heroes_list:
                                if hero['id'] == player['hero_id']:
                                    hero_list.append(hero['localized_name'])
                                    dire_content = (dire_content +
                                        hero['localized_name'] + " " +
                                        str(player['kills']) + "/" +
                                        str(player['deaths']) + "/" +
                                        str(player['assists']) + '\n')

                    bot.send_message(
                        cid,
                        'Winner:  *{title}* \n _Radiant:_ \n{radiant}\n _Dire:_\n{dire}\n'
                        .format(title=title, radiant=radiant_content, dire=dire_content)
                        + '[Dotabuff link]({url})'.format(url=url),
                        parse_mode="Markdown",
                        disable_web_page_preview=True)
                else:
                    bot.reply_to(
                        message,
                        "`There has been an error, the number {error} to be specific.`".format(error=request.status_code),
                        parse_mode="Markdown")
            else:
                bot.reply_to(message, "`wat`", parse_mode="Markdown")
        except Exception as ex:
            bot.reply_to(
                message,
                "There has been an error, its message is:\n `{error}`".format(error=ex.msg),
                parse_mode="Markdown")
示例#27
0
def meta_question(message):
    source = message.reply_to_message
    bot.reply_to(source, text=config.nometa)
    bot.delete_message(message_id=message.message_id, chat_id=message.chat.id)
示例#28
0
def fourtytwo(message):
    '''
    LOL
    '''

    bot.reply_to(message, "*В чем смысл жизни? 🤔*", parse_mode='Markdown')
示例#29
0
def punisher(message):
    """Gives RO to user who posted the message,
    deletes the message from chat,
    forwards the deleted message to the admins,
    triggers judgment buttons
    """

    session = Session()
    user_obj = session.query(User).get(message.from_user.id)
    if not user_obj:
        user_obj = User(message.from_user.id)
        session.add(user_obj)
    else:
        user_obj.msg_count -= 1
    session.commit()
    session.close()

    if r.get("spammer_{}".format(message.from_user.id)):
        bot.delete_message(chat_id=message.chat.id,
                           message_id=message.message_id)
        logger.info(
            "Message {} has been deleted without alerting the admins due to flooding"
            .format(message.message_id))
        return

    if message.from_user.id not in config.admin_ids:
        bot.restrict_chat_member(chat_id=config.chat_id,
                                 user_id=message.from_user.id)
        logger.info(
            "User {} has been restricted for leading to a channel".format(
                get_user(message.from_user)))

    r.set(message.message_id, 1)
    r.set("spammer_{}".format(message.from_user.id),
          1,
          ex=config.spammer_timeout)

    judgement_text = ("Reported user's ID: {} \n"
                      "Reported message's ID: {} \n"
                      "Что будем делать?".format(message.from_user.id,
                                                 message.message_id))
    keyboard = types.InlineKeyboardMarkup(row_width=2)
    btn_ban = types.InlineKeyboardButton(text="Отправить в бан",
                                         callback_data="ban")
    btn_release = types.InlineKeyboardButton(text="Снять РО",
                                             callback_data="release")
    keyboard.add(btn_ban, btn_release)

    for admin_id in config.admin_ids:
        try:
            reported = bot.forward_message(
                chat_id=admin_id,
                from_chat_id=config.chat_id,
                message_id=message.message_id,
            )
            bot.reply_to(reported, judgement_text, reply_markup=keyboard)
        except ApiException as e:
            if str(e.result) == config.unreachable_exc:
                continue

    bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)
    logger.info("Message {} has been successfully auto-reported".format(
        message.message_id))
示例#30
0
def captcha_switcher(message):
    config.CAPTCHA_ENABLED = not config.CAPTCHA_ENABLED
    bot.reply_to(
        message,
        text=f"Captcha: {'enabled' if config.CAPTCHA_ENABLED else 'disabled'}")