Пример #1
0
async def deny(context):
    """ Toggles denying of a user. """
    if not redis_status():
        await context.edit("Redis is offline, cannot operate.")
        return
    if len(context.parameter) != 1:
        await context.edit("Invalid argument.")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit("Unable to set flag on self.")
            return
        redis.set("denied.chat_id." + str(context.chat_id), "true")
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} added to denied chats.")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit("Unable to set flag on self.")
            return
        redis.delete("denied.chat_id." + str(context.chat_id))
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} removed from denied chats.")
    elif context.parameter[0] == "status":
        if redis.get("denied.chat_id." + str(context.chat_id)):
            await context.edit("Current chat is denied.")
        else:
            await context.edit("Current chat is not denied.")
    else:
        await context.edit("Invalid argument.")
Пример #2
0
async def force_subscribe_join(event: ChatAction.Event):
    if not redis_status():
        return
    if not (event.user_joined or event.user_added):
        return
    join_chat = redis.get(f"sub.chat_id.{event.chat_id}")
    if not join_chat:
        return
    else:
        join_chat = join_chat.decode()
    user = await event.get_user()
    if user.bot:
        return
    if redis.get(f"sub.chat_id.{event.chat_id}.{user.id}"):
        return
    try:
        try:
            await bot(GetParticipantRequest(join_chat, user.id))
        except ValueError:
            user_input = await event.get_input_user()
            await bot(GetParticipantRequest(join_chat, user_input))
        redis.set(f'sub.chat_id.{event.chat_id}.{user.id}', 'true')
        redis.expire(f'sub.chat_id.{event.chat_id}.{user.id}', 3600)
    except UserNotParticipantError:
        msg = await event.reply(
            f'[{user.first_name}](tg://user?id={user.id}) 您需要先加入频道 @{join_chat} 才能发言。'
        )
        await sleep(5)
        await msg.delete()
    except ChatAdminRequiredError:
        redis.delete(f"sub.chat_id.{event.chat_id}")
Пример #3
0
async def antichannelpin(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if len(context.parameter) != 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.set("antichannelpin." + str(context.chat_id), "true")
        await context.edit(f"已成功开启群组 {str(context.chat_id)} 的自动取消频道置顶功能。")
        await log(f"已成功开启群组 {str(context.chat_id)} 的自动取消频道置顶功能。")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        try:
            redis.delete("antichannelpin." + str(context.chat_id))
        except:
            await context.edit('emm...当前对话不存在于自动取消频道置顶功能列表中。')
            return
        await context.edit(f"已成功关闭群组 {str(context.chat_id)} 的自动取消频道置顶功能。")
        await log(f"已成功关闭群组 {str(context.chat_id)} 的自动取消频道置顶功能。")
    elif context.parameter[0] == "status":
        if redis.get("antichannelpin." + str(context.chat_id)):
            await context.edit('当前对话存在于自动取消频道置顶功能列表中。')
        else:
            await context.edit('当前对话不存在于自动取消频道置顶功能列表中。')
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
Пример #4
0
async def force_sub(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if len(context.parameter) != 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.delete(f"sub.chat_id.{context.chat_id}")
        await context.edit(f'成功关闭强制关注频道功能。')
    elif context.parameter[0] == "status":
        if redis.get(f"sub.chat_id.{context.chat_id}"):
            join_chat = redis.get(f"sub.chat_id.{context.chat_id}").decode()
            await context.edit(f'当前群组强制需要关注频道的频道为: @{join_chat} 。')
        else:
            await context.edit('当前群组未开启强制关注频道功能。')
    else:
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        sub_channel = context.parameter[0].replace('@', '')
        try:
            await context.client.get_participants(
                sub_channel, filter=ChannelParticipantsAdmins)
        except:
            await context.edit(f'设置失败:不是频道 @{sub_channel} 的管理员。')
            return
        redis.set(f"sub.chat_id.{context.chat_id}", sub_channel)
        await context.edit(f'已设置当前群组强制需要关注频道的频道为: @{sub_channel} 。')
Пример #5
0
async def deny(context):
    """ Toggles denying of a user. """
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 离线,无法运行。")
        return
    if len(context.parameter) != 1:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.set("denied.chat_id." + str(context.chat_id), "true")
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} 已被添加到自动拒绝对话列表中。")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.delete("denied.chat_id." + str(context.chat_id))
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} 已从自动拒绝对话列表中移除。")
    elif context.parameter[0] == "status":
        if redis.get("denied.chat_id." + str(context.chat_id)):
            await context.edit("emm...当前对话已被加入自动拒绝对话列表中。")
        else:
            await context.edit("emm...当前对话已从自动拒绝对话列表移除。")
    else:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
Пример #6
0
async def force_group(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if len(context.parameter) != 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.delete(f"group.chat_id.{context.chat_id}")
        await context.edit(f'成功关闭强制加入频道讨论群功能。')
    elif context.parameter[0] == "status":
        if redis.get(f"group.chat_id.{context.chat_id}"):
            await context.edit(f'当前群组已开启强制加入频道讨论群功能。')
        else:
            await context.edit('当前群组未开启强制加入频道讨论群功能。')
    else:
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        admins = await context.client.get_participants(
            context.chat, filter=ChannelParticipantsAdmins)
        if context.sender in admins:
            user = admins[admins.index(context.sender)]
            if not user.participant.admin_rights.delete_messages:
                await context.edit('无删除消息权限,拒绝开启此功能。')
                return
        redis.set(f"group.chat_id.{context.chat_id}", 'true')
        await context.edit(f'成功在当前群组开启强制加入频道讨论群功能。')
Пример #7
0
async def ghost(context):
    """ Toggles ghosting of a user. """
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 好像离线了,无法执行命令。")
        return
    if len(context.parameter) != 1:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.set("ghosted.chat_id." + str(context.chat_id), "true")
        await context.delete()
        await log(f"已成功将 ChatID {str(context.chat_id)} 添加到自动已读对话列表中。")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        try:
            redis.delete("ghosted.chat_id." + str(context.chat_id))
        except:
            await context.edit("emm...当前对话不存在于自动已读对话列表中。")
            return
        await context.delete()
        await log(f"已成功将 ChatID {str(context.chat_id)} 从自动已读对话列表中移除。")
    elif context.parameter[0] == "status":
        if redis.get("ghosted.chat_id." + str(context.chat_id)):
            await context.edit("emm...当前对话存在于自动已读对话列表中。")
        else:
            await context.edit("emm...当前对话不存在于自动已读对话列表中。")
    else:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
Пример #8
0
async def deny(context):
    """ Toggles denying of a user. """
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if len(context.parameter) != 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.set("denied.chat_id." + str(context.chat_id), "true")
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} {lang('deny_set')}")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.delete("denied.chat_id." + str(context.chat_id))
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} {lang('deny_cancel')}")
    elif context.parameter[0] == "status":
        if redis.get("denied.chat_id." + str(context.chat_id)):
            await context.edit(lang('deny_e_exist'))
        else:
            await context.edit(lang('deny_e_noexist'))
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
Пример #9
0
 async def _restart_complete_report():
     restart_args = redis.get("restart_edit")
     if restart_args:
         redis.delete("restart_edit")
         restart_args = restart_args.decode("utf-8")
         restart_msg, restart_chat = restart_args.split("|")
         await bot.edit_message(int(restart_chat), int(restart_msg),
                                lang('restart_complete'))
Пример #10
0
async def denyu(context):
    """ Toggles denying of a user. """
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 离线,无法运行。")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    uid = None
    offset = 0
    if len(context.parameter) != 2:
        reply_to_msg = await context.get_reply_message()
        if not reply_to_msg:
            await context.edit(
                "在某群中强制禁言某用户,需要删除他人消息权限,需要 redis。用法:回复某条消息,格式为 `-denyu <true|false|status>`"
            )
            return
        try:
            uid = reply_to_msg.sender.id
        except AttributeError:
            await context.edit("出错了呜呜呜 ~ 无法读取用户 id")
            return
        offset = 1
    else:
        uid = context.parameter[0]
    try:
        context.parameter[1 - offset]
    except IndexError:
        await context.edit("请指定参数 <true|false|status>!")
        return
    if context.parameter[1 - offset] == "true":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.set(f"denieduser.{context.chat_id}.{uid}", "true")
        await context.delete()
        await log(f"ChatID {context.chat_id} UserID {uid} 已被添加到自动拒绝对话列表中。")
    elif context.parameter[1 - offset] == "false":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.delete(f"denieduser.{context.chat_id}.{uid}")
        await context.delete()
        await log(f"ChatID {context.chat_id} UserID {uid} 已从自动拒绝对话列表中移除。")
    elif context.parameter[1 - offset] == "status":
        if redis.get(f"denieduser.{context.chat_id}.{uid}"):
            await context.edit("emm...当前对话的该用户已存在于自动拒绝对话列表中。")
        else:
            await context.edit("emm...当前对话不存在于自动拒绝对话列表中。")
    else:
        await context.edit("出错了呜呜呜 ~ 无效的参数。只能为 `<true|false|status>`。")
Пример #11
0
async def anti_channel_msg(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if context.chat_id == user_id or not context.is_group:
        await context.edit(lang('ghost_e_mark'))
        return
    if len(context.parameter) == 0:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    if context.parameter[0] == "true":
        data = await bot(GetFullChannelRequest(context.chat_id))
        if not data.full_chat.linked_chat_id:
            return await context.edit("当前群组未链接到频道,无法开启此功能。")
        redis.set("antichannelmsg." + str(context.chat_id), f"{data.full_chat.linked_chat_id}")
        await context.edit(f"已成功开启群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
        await log(f"已成功开启群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
    elif context.parameter[0] == "false":
        try:
            redis.delete("antichannelmsg." + str(context.chat_id))
        except:
            await context.edit('emm...当前对话不存在于自动删除频道消息并且封禁频道功能列表中。')
            return
        await context.edit(f"已成功关闭群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
        await log(f"已成功关闭群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
    elif context.parameter[0] == "add":
        data = redis.get("antichannelmsg." + str(context.chat_id))
        if not data:
            return await context.edit("emm...当前对话不存在于自动删除频道消息并且封禁频道功能列表中。")
        data = data.decode().split(" ")
        try:
            chat_id = context.parameter[1]
            channel_data = await bot(GetFullChannelRequest(int(chat_id)))  # noqa
        except TypeError:
            return await context.edit("频道 id 错误")
        except ValueError:
            return await context.edit("频道 id 不是 -100 开头的数字")
        except IndexError:
            return await context.edit("没有指定频道 id")
        data.append(str(channel_data.full_chat.id))
        redis.set("antichannelmsg." + str(context.chat_id), " ".join(data))
        await context.edit("添加频道到白名单成功。")
    elif context.parameter[0] == "status":
        if redis.get("antichannelmsg." + str(context.chat_id)):
            await context.edit('当前对话存在于自动删除频道消息并且封禁频道功能列表中。')
        else:
            await context.edit('当前对话不存在于自动删除频道消息并且封禁频道功能列表中。')
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
Пример #12
0
async def unpin_link_channel_message(context):
    """ Event handler to unpin linked channel messages. """
    if not redis_status():
        return
    if not redis.get("antichannelpin." + str(context.chat_id)):
        return
    try:
        if not isinstance(context.sender, Channel):
            return
    except:
        return
    await sleep(1)
    try:
        await context.unpin()
    except ChatAdminRequiredError:
        redis.delete("antichannelpin." + str(context.chat_id))
    except:
        pass
Пример #13
0
async def force_group_msg(context: Message):
    if not redis_status():
        return
    join_chat = redis.get(f"group.chat_id.{context.chat_id}")
    if not join_chat:
        return
    if redis.get(f"group.chat_id.{context.chat_id}.{context.sender_id}"):
        return
    try:
        if context.sender.bot:
            pass
    except AttributeError:
        return
    try:
        try:
            await bot(GetParticipantRequest(context.chat, context.sender_id))
        except ValueError:
            await bot.get_participants(context.chat)
            await bot(GetParticipantRequest(context.chat, context.sender_id))
        redis.set(f'group.chat_id.{context.chat_id}.{context.sender_id}',
                  'true')
        redis.expire(f'group.chat_id.{context.chat_id}.{context.sender_id}',
                     3600)
    except UserNotParticipantError:
        try:
            reply = await context.get_reply_message()
            try:
                reply = reply.id
            except AttributeError:
                reply = None
            await context.delete()
            msg = await bot.send_message(
                context.chat_id,
                f'[{context.sender.first_name}](tg://user?id={context.sender_id}) '
                f'您需要先加入频道讨论群才能发言。',
                reply_to=reply)
            await sleep(5)
            await msg.delete()
        except ChatAdminRequiredError:
            redis.delete(f"group.chat_id.{context.chat_id}")
    except ChatAdminRequiredError:
        redis.delete(f"group.chat_id.{context.chat_id}")
Пример #14
0
async def auto_process_channel_msg(context):
    """ Event handler to delete channel messages and ban channel. """
    if not redis_status():
        return
    if not context.is_group:
        return
    # 匿名管理员
    if not context.sender:
        return
    data = redis.get("antichannelmsg." + str(context.chat_id))
    if not data:
        return
    try:
        if not isinstance(context.sender, Channel):
            return
        data = data.decode().split(" ")
        # 白名单
        if str(context.sender.id) in data:
            return
        # 删除消息,封禁频道
        try:
            await context.delete()
            entity = await context.client.get_input_entity(context.chat_id)
            user = await context.client.get_input_entity(context.sender.id)
            await context.client(EditBannedRequest(
                channel=entity,
                participant=user,
                banned_rights=ChatBannedRights(
                    until_date=None, view_messages=True)
            ))
        except ChatAdminRequiredError:
            redis.delete("antichannelmsg." + str(context.chat_id))
    except:
        return
    try:
        await context.unpin()
    except ChatAdminRequiredError:
        redis.delete("antichannelmsg." + str(context.chat_id))
    except:
        pass
Пример #15
0
async def force_subscribe_msg(context: Message):
    if not redis_status():
        return
    join_chat = redis.get(f"sub.chat_id.{context.chat_id}")
    if not join_chat:
        return
    if redis.get(f"sub.chat_id.{context.chat_id}.{context.sender_id}"):
        return
    else:
        join_chat = join_chat.decode()
    try:
        if context.sender.bot:
            return
    except AttributeError:
        return
    try:
        try:
            await bot(GetParticipantRequest(join_chat, context.sender_id))
        except ValueError:
            await bot.get_participants(context.chat)
            await bot(GetParticipantRequest(join_chat, context.sender_id))
        redis.set(f'sub.chat_id.{context.chat_id}.{context.sender_id}', 'true')
        redis.expire(f'sub.chat_id.{context.chat_id}.{context.sender_id}',
                     3600)
    except UserNotParticipantError:
        try:
            await context.delete()
            try:
                msg = await bot.send_message(
                    context.chat_id,
                    f'[{context.sender.first_name}](tg://user?id={context.sender_id}) '
                    f'您需要先加入频道 @{join_chat} 才能发言。')
                await sleep(5)
                await msg.delete()
            except ValueError:
                pass
        except ChatAdminRequiredError:
            redis.delete(f"sub.chat_id.{context.chat_id}")
    except ChatAdminRequiredError:
        redis.delete(f"sub.chat_id.{context.chat_id}")
Пример #16
0
async def settings(context):
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 离线,无法运行")
        await del_msg(context, 10)
        return
    params = []
    for p in context.parameter:
        if len(p.split()) != 0:
            params.append(p)
    if len(params) > 0 and params[0] == "bot":
        if len(params) == 3 and is_num(params[1]):
            redis.set("msgst.bot_id", params[1])
            redis.set("msgst.bot_un", params[2])
            await context.edit("设置成功")
            await del_msg(context, 10)
        elif len(params) == 2 and params[1] == "clear":
            redis.delete("msgst.bot_id")
            redis.delete("msgst.bot_un")
            await context.edit("清除成功")
            await del_msg(context, 10)
    else:
        await context.edit("参数错误")
        await del_msg(context, 10)
Пример #17
0
async def repeat(context):
    if not context.is_group:
        await context.edit('请在群组中运行。')
        return
    if not redis_status():
        await context.edit('出错了呜呜呜 ~ Redis 数据库离线。')
        return
    reply = await context.get_reply_message()
    if not reply or not reply.sender:
        await context.edit('请回复一个用户。')
        return
    uid = reply.sender_id
    if len(context.parameter) == 1:
        if redis.get(f'repeat_{context.chat_id}_{uid}'):
            await context.edit('此用户存在于自动复读列表。')
        else:
            await context.edit('此用户不存在于自动复读列表。')
        return
    if redis.get(f'repeat_{context.chat_id}_{uid}'):
        redis.delete(f'repeat_{context.chat_id}_{uid}')
        await context.edit('从自动复读列表移除成功。')
    else:
        redis.set(f'repeat_{context.chat_id}_{uid}', 'true')
        await context.edit('添加到自动复读列表成功。')
Пример #18
0
async def auto_process_channel_msg(context):
    """ Event handler to delete channel messages and ban channel. """
    if not redis_status():
        return
    if not context.is_group:
        return
    # 匿名管理员
    if not context.sender:
        return
    data = redis.get("antichannelmsg." + str(context.chat_id))
    if not data:
        return
    filter_data = redis.get("antichannelmsg.filter:" + str(context.chat_id))
    if filter_data is not None:
        participants_count = redis.get("antichannelmsg.participants_count:" +
                                       str(context.chat_id))
        if participants_count is None:
            expire = 300
            try:
                channel_data = await bot(
                    GetFullChannelRequest(int(context.sender.id)))
                participants_count = channel_data.full_chat.participants_count
                expire = 3600
            except:  # noqa
                participants_count = 0
            redis.set("antichannelmsg.participants_count:" +
                      str(context.chat_id),
                      participants_count,
                      ex=expire)
        else:
            try:
                participants_count = int(participants_count)
            except ValueError:
                participants_count = 0
        try:
            filter_int = int(filter_data)
        except ValueError:
            filter_int = -1
    try:
        if not isinstance(context.sender, Channel):
            return
        data = data.decode().split(" ")
        # 白名单
        if str(context.sender.id) in data:
            return
        # 频道订阅人数检测
        if filter_data is not None and (filter_int != -1
                                        and participants_count >= filter_int):
            return

        # 删除消息,封禁频道
        try:
            await context.delete()
            entity = await context.client.get_input_entity(context.chat_id)
            user = await context.client.get_input_entity(context.sender.id)
            await context.client(
                EditBannedRequest(channel=entity,
                                  participant=user,
                                  banned_rights=ChatBannedRights(
                                      until_date=None, view_messages=True)))
        except ChatAdminRequiredError:
            redis.delete("antichannelmsg." + str(context.chat_id))
    except:
        return
    try:
        await context.unpin()
    except ChatAdminRequiredError:
        redis.delete("antichannelmsg." + str(context.chat_id))
    except:
        pass
Пример #19
0
async def shift_set(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if not 1 < len(context.parameter) < 4:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    if context.parameter[0] == "set":
        if len(context.parameter) != 3:
            await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
            return
        # 检查来源频道
        try:
            channel = await context.client.get_entity(int(context.parameter[1])
                                                      )
            if not channel.broadcast:
                await context.edit("出错了呜呜呜 ~ 无法识别的来源对话。")
                return
            channel = int(f'-100{channel.id}')
        except Exception:
            try:
                channel = await context.client.get_entity(context.parameter[1])
                if not channel.broadcast:
                    await context.edit("出错了呜呜呜 ~ 无法识别的来源对话。")
                    return
                channel = int(f'-100{channel.id}')
            except Exception:
                await context.edit("出错了呜呜呜 ~ 无法识别的来源对话。")
                return
        if channel in [-1001441461877]:
            await context.edit('出错了呜呜呜 ~ 此对话位于白名单中。')
            return
        # 检查目标频道
        try:
            to = int(context.parameter[2])
        except Exception:
            try:
                to = await context.client.get_entity(context.parameter[2])
                if to.broadcast or to.gigagroup or to.megagroup:
                    to = int(f'-100{to.id}')
                else:
                    to = to.id
            except Exception:
                await context.edit("出错了呜呜呜 ~ 无法识别的目标对话。")
                return
        if to in [-1001441461877]:
            await context.edit('出错了呜呜呜 ~ 此对话位于白名单中。')
            return
        redis.set("shift." + str(channel), f"{to}")
        await context.edit(f"已成功配置将对话 {channel} 的新消息转发到 {to} 。")
        await log(f"已成功配置将对话 {channel} 的新消息转发到 {to} 。")
    elif context.parameter[0] == "del":
        if len(context.parameter) != 2:
            await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
            return
        # 检查来源频道
        try:
            channel = int(context.parameter[1])
        except Exception:
            try:
                channel = (await
                           context.client.get_entity(context.parameter[1])).id
                if channel.broadcast or channel.gigagroup or channel.megagroup:
                    channel = int(f'-100{channel.id}')
            except Exception:
                await context.edit("出错了呜呜呜 ~ 无法识别的来源对话。")
                return
        try:
            redis.delete("shift." + str(channel))
        except:
            await context.edit('emm...当前对话不存在于自动转发列表中。')
            return
        await context.edit(f"已成功关闭对话 {str(channel)} 的自动转发功能。")
        await log(f"已成功关闭对话 {str(channel)} 的自动转发功能。")
    elif context.parameter[0] == "backup":
        if len(context.parameter) != 3:
            await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
            return
        # 检查来源频道
        try:
            channel = await context.client.get_entity(int(context.parameter[1])
                                                      )
            if not channel.broadcast:
                await context.edit("出错了呜呜呜 ~ 无法识别的来源对话。")
                return
            channel = int(f'-100{channel.id}')
        except Exception:
            try:
                channel = await context.client.get_entity(context.parameter[1])
                if not channel.broadcast:
                    await context.edit("出错了呜呜呜 ~ 无法识别的来源对话。")
                    return
                channel = int(f'-100{channel.id}')
            except Exception:
                await context.edit("出错了呜呜呜 ~ 无法识别的来源对话。")
                return
        if channel in [-1001441461877]:
            await context.edit('出错了呜呜呜 ~ 此对话位于白名单中。')
            return
        # 检查目标频道
        try:
            to = int(context.parameter[2])
        except Exception:
            try:
                to = await context.client.get_entity(context.parameter[2])
                if to.broadcast or to.gigagroup or to.megagroup:
                    to = int(f'-100{to.id}')
                else:
                    to = to.id
            except Exception:
                await context.edit("出错了呜呜呜 ~ 无法识别的目标对话。")
                return
        if to in [-1001441461877]:
            await context.edit('出错了呜呜呜 ~ 此对话位于白名单中。')
            return
        # 开始遍历消息
        await context.edit(f'开始备份频道 {channel} 到 {to} 。')
        async for msg in context.client.iter_messages(int(channel),
                                                      reverse=True):
            await sleep(uniform(0.5, 1.0))
            try:
                await forward_msg(context, msg, to)
            except BaseException:
                pass
        await context.edit(f'备份频道 {channel} 到 {to} 已完成。')
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
Пример #20
0
async def reply_set(context):
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 离线,无法运行")
        await del_msg(context, 5)
        return
    chat_id = context.chat_id
    params = context.parameter
    redis_data = f"keyword.{chat_id}.settings"
    if len(params) >= 1 and params[0] == "global":
        redis_data = "keyword.settings"
        del params[0]
    elif len(params) >= 2 and params[0] in ("plain", "regex") and is_num(params[1]):
        rule_data = get_rule(chat_id, params[0], params[1])
        if rule_data:
            redis_data = f"keyword.{chat_id}.single.{params[0]}.{rule_data}"
            del params[0:2]
    settings_dict = get_redis(redis_data)
    cmd_dict = {
        "help": (1,),
        "mode": (2,),
        "list": (2, 3),
        "freq": (2,),
        "trig": (2,),
        "show": (1,),
        "cache": (2,),
        "redir": (2,),
        "status": (2,),
        "clear": (1,)
    }
    if len(params) < 1:
        await context.edit("参数错误")
        await del_msg(context, 5)
        return
    if params[0] in cmd_dict and len(params) in cmd_dict[params[0]]:
        if params[0] == "help":
            await context.edit('''
`-replyset show` 或
`-replyset clear` 或
`-replyset mode <0/1/clear>` ( 0 表示黑名单,1 表示白名单 ) 或
`-replyset list <add/del/show/clear> [user_id]` 或
`-replyset freq <float/clear>` ( float 表示一个正的浮点数,clear 为清除 ) 或
`-replyset trig <0/1/clear>` ( 0 为关闭,1 为开启,clear 为清除 ) 或
`-replyset cache <0/1/clear>` ( 0 为关闭,1 为开启 ) 或
`-replyset status <0/1/clear>` ( 0 为关闭,1 为开启 ) 。
在 `-replyset` 后面加上 `global` 即为全局设置。
在 `-replyset` 后面加上 `plain/regex` 规则序号 可以单独设置一条规则。''')
            await del_msg(context, 15)
            return
        elif params[0] == "show":
            defaults = {
                "mode": "未设置 (默认黑名单)",
                "list": "未设置 (默认为空)",
                "freq": "未设置 (默认为 1)",
                "trig": "未设置 (默认关闭)",
                "cache": "未设置 (默认关闭)",
                "redir": "未设置 (默认关闭)",
                "status": "未设置 (默认开启)"
            }
            msg = "Settings: \n"
            for k, v in defaults.items():
                msg += f"`{k}` -> `{settings_dict[k] if k in settings_dict else v}`\n"
            await context.edit(msg)
            return
        elif params[0] == "mode":
            if params[1] in ("0", "1"):
                settings_dict["mode"] = params[1]
                redis.set(redis_data, save_rules(settings_dict, None))
                if params[1] == "0":
                    await context.edit("模式已更改为黑名单")
                elif params[1] == "1":
                    await context.edit("模式已更改为白名单")
                await del_msg(context, 5)
                return
            elif params[1] == "clear":
                if "mode" in settings_dict:
                    del settings_dict["mode"]
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("清除成功")
                await del_msg(context, 5)
                return
            else:
                await context.edit("参数错误")
                await del_msg(context, 5)
                return
        elif params[0] == "list":
            if params[1] == "show" and len(params) == 2:
                user_list = settings_dict.get("list", None)
                if user_list:
                    msg = "List: \n"
                    for p in user_list.split(","):
                        msg += f"`{p}`\n"
                    await context.edit(msg)
                    return
                else:
                    await context.edit("列表为空")
                    await del_msg(context, 5)
                    return
            elif params[1] == "add" and len(params) == 3:
                if is_num(params[2]):
                    tmp = settings_dict.get("list", None)
                    if not tmp:
                        settings_dict["list"] = params[2]
                    else:
                        settings_dict["list"] += f",{params[2]}"
                    redis.set(redis_data, save_rules(settings_dict, None))
                    await context.edit("添加成功")
                    await del_msg(context, 5)
                    return
                else:
                    await context.edit("user_id 需为整数")
                    await del_msg(context, 5)
                    return
            elif params[1] == "del" and len(params) == 3:
                if is_num(params[2]):
                    tmp = settings_dict.get("list", None)
                    if tmp:
                        user_list = settings_dict["list"].split(",")
                        if params[2] in user_list:
                            user_list.remove(params[2])
                            settings_dict["list"] = ",".join(user_list)
                            redis.set(redis_data, save_rules(settings_dict, None))
                            await context.edit("删除成功")
                            await del_msg(context, 5)
                            return
                        else:
                            await context.edit("user_id 不在列表")
                            await del_msg(context, 5)
                            return
                    else:
                        await context.edit("列表为空")
                        await del_msg(context, 5)
                        return
                else:
                    await context.edit("user_id 需为整数")
                    await del_msg(context, 5)
                    return
            elif params[1] == "clear" and len(params) == 2:
                if "list" in settings_dict:
                    del settings_dict["list"]
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("清除成功")
                await del_msg(context, 5)
                return
            else:
                await context.edit("参数错误")
                await del_msg(context, 5)
                return
        elif params[0] == "freq":
            if redis_data == f"keyword.{chat_id}.settings":
                if params[1] == "clear":
                    if "freq" in settings_dict:
                        del settings_dict["freq"]
                    redis.set(redis_data, save_rules(settings_dict, None))
                    await context.edit("清除成功")
                    await del_msg(context, 5)
                    return
                else:
                    try:
                        tmp = float(params[1])
                        if tmp > 0:
                            settings_dict["freq"] = params[1]
                            redis.set(redis_data, save_rules(settings_dict, None))
                            await context.edit("设置成功")
                            await del_msg(context, 5)
                            return
                        else:
                            await context.edit("频率需为正数")
                            await del_msg(context, 5)
                            return
                    except:
                        await context.edit("频率需为正数")
                        await del_msg(context, 5)
                        return
            else:
                await context.edit("此项无法使用全局设置和单独设置")
                return
        elif params[0] == "trig":
            if params[1] == "0":
                settings_dict["trig"] = "0"
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("已关闭自我触发")
                await del_msg(context, 5)
                return
            elif params[1] == "1":
                settings_dict["trig"] = "1"
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("已开启自我触发")
                await del_msg(context, 5)
                return
            elif params[1] == "clear":
                if "trig" in settings_dict:
                    del settings_dict["trig"]
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("已清除自我触发设置")
                await del_msg(context, 5)
                return
            else:
                await context.edit("参数错误")
                await del_msg(context, 5)
                return
        elif params[0] == "cache":
            if params[1] == "0":
                settings_dict["cache"] = "0"
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("已关闭缓存功能")
                await del_msg(context, 5)
                return
            elif params[1] == "1":
                settings_dict["cache"] = "1"
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("已开启缓存功能")
                await del_msg(context, 5)
                return
            elif params[1] == "remove":
                if redis_data == "keyword.settings":
                    rmtree("data/keyword_cache")
                elif redis_data.split(".")[2] == "single":
                    rmtree(f"data/keyword_cache/{chat_id}/"
                           f"{redis_data.split('.')[3]}:{redis_data.split('.')[4]}")
                else:
                    rmtree(f"data/keyword_cache/{chat_id}")
                await context.edit("已删除缓存")
                await del_msg(context, 5)
                return
            elif params[1] == "clear":
                if "cache" in settings_dict:
                    del settings_dict["cache"]
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("清除成功")
                await del_msg(context, 5)
                return
            else:
                await context.edit("参数错误")
                await del_msg(context, 5)
                return
        elif params[0] == "redir":
            if params[1] == "0":
                settings_dict["redir"] = "0"
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("已关闭回复穿透")
                await del_msg(context, 5)
                return
            elif params[1] == "1":
                settings_dict["redir"] = "1"
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("已开启回复穿透")
                await del_msg(context, 5)
                return
            elif params[1] == "clear":
                if "redir" in settings_dict:
                    del settings_dict["redir"]
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("已清除回复穿透设置")
                await del_msg(context, 5)
                return
            else:
                await context.edit("参数错误")
                await del_msg(context, 5)
                return
        elif params[0] == "status":
            if redis_data == f"keyword.{chat_id}.settings":
                if params[1] == "0":
                    settings_dict["status"] = "0"
                    redis.set(redis_data, save_rules(settings_dict, None))
                    await context.edit("已关闭此聊天的关键词回复")
                    await del_msg(context, 5)
                    return
                elif params[1] == "1":
                    settings_dict["status"] = "1"
                    redis.set(redis_data, save_rules(settings_dict, None))
                    await context.edit("已开启此聊天的关键词回复")
                    await del_msg(context, 5)
                    return
                elif params[1] == "clear":
                    if "status" in settings_dict:
                        del settings_dict["status"]
                    redis.set(redis_data, save_rules(settings_dict, None))
                    await context.edit("已清除此设置")
                    await del_msg(context, 5)
                    return
                else:
                    await context.edit("参数错误")
                    await del_msg(context, 5)
                    return
            else:
                await context.edit("此项无法使用全局设置和单独设置")
                return
        elif params[0] == "clear":
            redis.delete(redis_data)
            await context.edit("清除成功")
            await del_msg(context, 5)
            return
    else:
        await context.edit("参数错误")
        await del_msg(context, 5)
        return
Пример #21
0
async def reply(context):
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 离线,无法运行")
        await del_msg(context, 5)
        return
    chat_id = context.chat_id
    plain_dict = get_redis(f"keyword.{chat_id}.plain")
    regex_dict = get_redis(f"keyword.{chat_id}.regex")
    params = context.parameter
    params = " ".join(params)
    placeholder = random_str()
    params = params.replace(r"\'", placeholder)
    tmp_parse = params.split("'")
    parse = []
    for i in range(len(tmp_parse)):
        if len(tmp_parse[i].split()) != 0:
            parse.append(tmp_parse[i])
    if len(parse) == 0 or (
            len(parse[0].split()) == 1 and parse[0].split()[0] in ("new", "del", "delid", "clear")) or len(
            parse[0].split()) > 2:
        await context.edit(
            "[Code: -1] 格式错误,格式为 `-keyword` 加上 `new <plain|regex> '<规则>' '<回复信息>'` 或者 "
            "`del <plain|regex> '<规则>'` 或者 `list` 或者 `clear <plain|regex>`")
        await del_msg(context, 10)
        return
    else:
        parse[0] = parse[0].split()
    if parse[0][0] == "new" and len(parse) == 3:
        if parse[0][1] == "plain":
            plain_dict[parse[1]] = parse[2]
            redis.set(f"keyword.{chat_id}.plain", save_rules(plain_dict, placeholder))
        elif parse[0][1] == "regex":
            regex_dict[parse[1]] = parse[2]
            redis.set(f"keyword.{chat_id}.regex", save_rules(regex_dict, placeholder))
        else:
            await context.edit(
            "[Code: -1] 格式错误,格式为 `-keyword` 加上 `new <plain|regex> '<规则>' '<回复信息>'` 或者 "
            "`del <plain|regex> '<规则>'` 或者 `list` 或者 `clear <plain|regex>`")
            await del_msg(context, 10)
            return
        await context.edit("设置成功")
        await del_msg(context, 5)
    elif parse[0][0] in ("del", "delid") and len(parse) == 2:
        if parse[0][0] == "delid":
            parse[1] = get_rule(chat_id, parse[0][1], parse[1])
            if parse[1]:
                parse[1] = decode(parse[1])
        if parse[0][1] == "plain":
            if parse[1] and parse[1] in plain_dict:
                redis.delete(f"keyword.{chat_id}.single.plain.{encode(parse[1])}")
                plain_dict.pop(parse[1])
                redis.set(f"keyword.{chat_id}.plain", save_rules(plain_dict, placeholder))
            else:
                await context.edit("规则不存在")
                await del_msg(context, 5)
                return
        elif parse[0][1] == "regex":
            if parse[1] and parse[1] in regex_dict:
                redis.delete(f"keyword.{chat_id}.single.regex.{encode(parse[1])}")
                regex_dict.pop(parse[1])
                redis.set(f"keyword.{chat_id}.regex", save_rules(regex_dict, placeholder))
            else:
                await context.edit("规则不存在")
                await del_msg(context, 5)
                return
        else:
            await context.edit(
            "[Code: -1] 格式错误,格式为 `-keyword` 加上 `new <plain|regex> '<规则>' '<回复信息>'` 或者 "
            "`del <plain|regex> '<规则>'` 或者 `list` 或者 `clear <plain|regex>`")
            await del_msg(context, 10)
            return
        await context.edit("删除成功")
        await del_msg(context, 5)
    elif parse[0][0] == "list" and len(parse) == 1:
        plain_msg = "Plain: \n"
        index = 0
        for k, v in plain_dict.items():
            plain_msg += f"`{index}`: `{k}` -> `{v}`\n"
            index += 1
        regex_msg = "Regex: \n"
        index = 0
        for k, v in regex_dict.items():
            regex_msg += f"`{index}`: `{k}` -> `{v}`\n"
            index += 1
        await context.edit(plain_msg + "\n" + regex_msg)
    elif parse[0][0] == "clear" and len(parse) == 1:
        if parse[0][1] == "plain":
            for k in plain_dict.keys():
                redis.delete(f"keyword.{chat_id}.single.plain.{encode(k)}")
            redis.set(f"keyword.{chat_id}.plain", "")
        elif parse[0][1] == "regex":
            for k in regex_dict.keys():
                redis.delete(f"keyword.{chat_id}.single.regex.{encode(k)}")
            redis.set(f"keyword.{chat_id}.regex", "")
        else:
            await context.edit("参数错误")
            await del_msg(context, 5)
            return
        await context.edit("清除成功")
        await del_msg(context, 5)
    else:
        await context.edit(
            "[Code: -1] 格式错误,格式为 `-keyword` 加上 `new <plain|regex> '<规则>' '<回复信息>'` 或者 "
            "`del <plain|regex> '<规则>'` 或者 `list` 或者 `clear <plain|regex>`")
        await del_msg(context, 10)
        return
Пример #22
0
async def auto_del(context: Message):
    try:
        chat_id = context.chat_id
        # 读取参数
        args = context.arguments if context.arguments is not None else ""
        args = args.strip()
        reply = await context.get_reply_message()

        if not redis_status():
            await edit(context, f"出错了呜呜呜 ~ 数据库离线。")
            return
        if not reply:
            await edit(context, f"出错了呜呜呜 ~ 没有回复一条消息。")
            return
        if not reply.sender:
            await edit(context, f"出错了呜呜呜 ~ 无法获取回复的用户。")
            return
        if not context.is_group:
            await edit(context, f"出错了呜呜呜 ~ 没有在群组中执行。")
            return
        uid = reply.sender.id
        # 处理参数
        if len(args) == 0:
            await edit(context, "参数不能为空。使用 -help autodel 以查看帮助。")
            return
        if args.find("cancel") == -1 and not any(char.isdigit()
                                                 for char in args):
            await edit(context, "指定的参数中似乎没有时间长度。")
            return
        if args.find("cancel") == -1 and all(char.isdigit() for char in args):
            await edit(context, "请指定时间长度的单位。")
            return
        if args.find(":") != -1 or args.find("-") != -1:
            await edit(context, "请使用相对时间长度,而非绝对时间长度:不能含 : 或 -。")
            return
        # 处理取消
        if args.startswith("cancel"):
            if redis.get(f"autodel.{chat_id}.{uid}"):
                redis.delete(f"autodel.{chat_id}.{uid}")
                await context.edit('成功在当前群取消定时删除所回复对象的消息。')
            else:
                await context.edit('未在当前群启用定时删除所回复对象的消息。')
            return
        # 解析时间长度
        offset = local_time_offset() // 3600
        sign = "+" if offset >= 0 else "-"
        offset = abs(offset)
        offset_str = str(offset)
        offset_str = offset_str if len(offset_str) == 2 else f"0{offset_str}"

        settings = {'TIMEZONE': f'{sign}{offset_str}00'}
        dt = dateparser.parse(args, settings=settings)

        if dt is None:
            await edit(context, "无法解析所指定的时间长度。")
            return

        delta = time.time() - dt.timestamp()
        if delta <= 3:
            await edit(context, "所指定的时间长度过短。")
            return
        # 写入数据库
        redis.set(f"autodel.{chat_id}.{uid}", f"{delta}")
        await edit(context, "成功在当前群启用定时删除所回复对象的消息。")
        return
    except Exception as e:
        await edit(context, f"Error: {str(e)}")
    return
Пример #23
0
async def sticker(context):
    """ Fetches images/stickers and add them to your pack. """
    # 首先解封 sticker Bot
    try:
        await context.client(UnblockRequest(id=429000))
    except:
        pass
    pic_round = False
    is_batch = False
    to_sticker_set = False
    package_name = ""
    if redis_status():
        if redis.get("sticker.round"):
            pic_round = True

        if len(context.parameter) >= 1:
            # s merge
            await log(f"{context.parameter}")
            if context.parameter[0] == "merge" or context.parameter[0] == "m":
                is_batch = True
                # s merge png <package_name> <number>
                try:
                    if context.parameter[3].isnumeric():
                        if "png" in context.parameter[1]:
                            pic_round = False
                        else:
                            pic_round = True
                        package_name = context.parameter[2]
                except:
                    # 异常,多半是数组越界,不处理,继续参数校验
                    pass
                try:
                    # s merge <package_name> <number>
                    if context.parameter[2].isnumeric():
                        if "png" in context.parameter[1]:
                            pic_round = False
                            package_name = context.parameter[2]
                        else:
                            package_name = context.parameter[1]
                    # s merge png <package_name>
                    elif "png" in context.parameter[1]:
                        pic_round = False
                        package_name = context.parameter[2]
                    # s merge <package_name> <number>
                    else:
                        package_name = context.parameter[1]

                except:
                    # 异常,多半是数组越界
                    # s merge <package_name>
                    try:
                        if "png" in context.parameter[1]:
                            raise Exception()
                        package_name = context.parameter[1]
                    except:
                        # 命令错误
                        try:
                            await context.edit(lang('merge_command_error'))
                        except:
                            pass
                        return

            elif context.parameter[0] == "to":
                pass
            # s <png | number> | error
            else:
                if context.parameter[0] == "set_round":
                    if pic_round:
                        redis.delete("sticker.round")
                        try:
                            await context.edit(lang('us_change_rounding_false')
                                               )
                        except:
                            pass
                    else:
                        redis.set("sticker.round", "true")
                        try:
                            await context.edit(lang('us_change_rounding_true'))
                        except:
                            pass
                    return
                elif "png" in context.parameter[0]:
                    pic_round = False
                    # s <number>
                elif context.parameter[0].isnumeric():
                    pass
                elif isEmoji(context.parameter[0]) or len(
                        context.parameter[0]) == 1:
                    await log(f"emoji:{context.parameter[0]}")
                    pass
                else:
                    try:
                        await context.edit(lang('merge_command_error'))
                    except:
                        pass
                    return

    # 是否添加到指定贴纸包
    if len(context.parameter) >= 1:
        if "to" in context.parameter:
            if len(context.parameter) == 3:  # <emoji> to <sticker_pack>
                to_sticker_set = context.parameter[2]
                if redis_status():
                    redis.set("sticker.to", to_sticker_set)
            if len(context.parameter) == 2:
                to_sticker_set = context.parameter[1]
                if redis_status():
                    redis.set("sticker.to", to_sticker_set)
            else:
                if redis_status():
                    if redis.get("sticker.to"):
                        to_sticker_set = redis.get("sticker.to").decode()
                    else:
                        await context.edit(lang("sticker_to_no"))
                        return
                else:
                    await context.edit(lang("sticker_to_no"))
                    return

    user = await bot.get_me()
    if not user.username:
        user.username = user.first_name

    custom_emoji = False
    animated = False
    emoji = ""

    if is_batch:
        # 多张
        """ merge every single sticker after the message you replied to. """
        if not context.reply_to_msg_id:
            await context.edit(lang('not_reply'))
            return
        input_chat = await context.get_input_chat()
        count = 0
        scount = 0
        result = ""
        if context.parameter[0] == "m":
            message = await context.get_reply_message()
            await single_sticker(animated, context, custom_emoji, emoji,
                                 message, pic_round, user, package_name,
                                 to_sticker_set)
        else:
            async for message in context.client.iter_messages(
                    input_chat, min_id=context.reply_to_msg_id):
                count += 1
                if message and message.media:
                    scount += 1
                    try:
                        await log(
                            f"{lang('merge_processing_left')}{count}{lang('merge_processing_right')}"
                        )
                        if not silent:
                            await context.edit(
                                f"{lang('merge_processing_left')}{count}{lang('merge_processing_right')}"
                            )
                    except:
                        pass
                    result = await single_sticker(animated, context,
                                                  custom_emoji, emoji, message,
                                                  pic_round, user,
                                                  package_name, to_sticker_set)
                    await sleep(.5)
            try:
                await context.edit(
                    f"{result}\n"
                    f"{lang('merge_total_processed_left')}{scount}{lang('merge_total_processed_right')}",
                    parse_mode='md')
            except:
                pass
        await sleep(5)
        try:
            await context.delete()
        except:
            pass
    else:
        # 单张收集图片
        message = await context.get_reply_message()
        try:
            await single_sticker(animated, context, custom_emoji, emoji,
                                 message, pic_round, user, "", to_sticker_set)
        except FileExistsError:
            await context.edit(lang("sticker_to_full"))
Пример #24
0
async def eat(context: NewMessage.Event):
    assert isinstance(context.message, Message)
    if len(context.parameter) > 2:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    diu_round = False
    from_user = user_object = context.sender
    from_user_id = await get_full_id(from_user)
    if context.reply_to_msg_id:
        reply_message = await context.get_reply_message()
        try:
            user_id = reply_message.sender_id
        except AttributeError:
            await context.edit("出错了呜呜呜 ~ 无效的参数。")
            return
        if user_id > 0:
            target_user = await context.client(GetFullUserRequest(user_id))
            target_user_id = target_user.user.id
        else:
            target_user = await context.client(GetFullChannelRequest(user_id))
            target_user_id = target_user.full_chat.id
    else:
        user_raw = ""
        if len(context.parameter) == 1 or len(context.parameter) == 2:
            user_raw = user = context.parameter[0]
            if user.isnumeric():
                user = int(user)
        else:
            user = from_user_id
        if context.message.entities is not None:
            if isinstance(context.message.entities[0], MessageEntityMentionName):
                target_user = await context.client(GetFullUserRequest(context.message.entities[0].user_id))
                target_user_id = target_user.user.id
            elif isinstance(context.message.entities[0], MessageEntityPhone):
                if user > 0:
                    target_user = await context.client(GetFullUserRequest(user))
                    target_user_id = target_user.user.id
                else:
                    target_user = await context.client(GetFullChannelRequest(user))
                    target_user_id = target_user.full_chat.id
            elif isinstance(context.message.entities[0], MessageEntityBotCommand):
                target_user = await context.client(GetFullUserRequest(user_object.id))
                target_user_id = target_user.user.id
            else:
                return await context.edit("出错了呜呜呜 ~ 参数错误。")
        elif user_raw[:1] in [".", "/", "-", "!"]:
            target_user_id = await get_full_id(from_user)
        else:
            try:
                user_object = await context.client.get_entity(user)
                target_user_id = await get_full_id(user_object)
            except (TypeError, ValueError, OverflowError, StructError) as exception:
                if str(exception).startswith("Cannot find any entity corresponding to"):
                    await context.edit("出错了呜呜呜 ~ 指定的用户不存在。")
                    return
                if str(exception).startswith("No user has"):
                    await context.edit("出错了呜呜呜 ~ 指定的道纹不存在。")
                    return
                if str(exception).startswith("Could not find the input entity for") or isinstance(exception,
                                                                                                  StructError):
                    await context.edit("出错了呜呜呜 ~ 无法通过此 UserID 找到对应的用户。")
                    return
                if isinstance(exception, OverflowError):
                    await context.edit("出错了呜呜呜 ~ 指定的 UserID 已超出长度限制,您确定输对了?")
                    return
                raise exception
    photo = await context.client.download_profile_photo(
        target_user_id,
        "plugins/eat/" + str(target_user_id) + ".jpg",
        download_big=True
    )

    reply_to = context.message.reply_to_msg_id
    if exists("plugins/eat/" + str(target_user_id) + ".jpg"):
        for num in range(1, max_number + 1):
            print(num)
            if not exists('plugins/eat/eat' + str(num) + '.png'):
                re = get(f'{git_source}eat/eat' + str(num) + '.png')
                with open('plugins/eat/eat' + str(num) + '.png', 'wb') as bg:
                    bg.write(re.content)
            if not exists('plugins/eat/mask' + str(num) + '.png'):
                re = get(f'{git_source}eat/mask' + str(num) + '.png')
                with open('plugins/eat/mask' + str(num) + '.png', 'wb') as ms:
                    ms.write(re.content)
        number = randint(1, max_number)
        try:
            p1 = 0
            p2 = 0
            if len(context.parameter) == 1:
                p1 = context.parameter[0]
                if p1[0] == ".":
                    diu_round = True
                    if len(p1) > 1:
                        try:
                            p2 = int("".join(p1[1:]))
                        except:
                            # 可能也有字母的参数
                            p2 = "".join(p1[1:])
                elif p1[0] == "-":
                    if len(p1) > 1:
                        try:
                            p2 = int("".join(p1[1:]))
                        except:
                            # 可能也有字母的参数
                            p2 = "".join(p1[1:])
                    if p2:
                        redis.set("eat.default-config", p2)
                        await context.edit(f"已经设置默认配置为:{p2}")
                    else:
                        redis.delete("eat.default-config")
                        await context.edit(f"已经清空默认配置")
                    return
                elif p1[0] == "/":
                    await context.edit(f"正在更新远程配置文件")
                    if len(p1) > 1:
                        # 获取参数中的url
                        p2 = "".join(p1[1:])
                        if p2 == "delete":
                            redis.delete(configFileRemoteUrlKey)
                            await context.edit(f"已清空远程配置文件url")
                            return
                        if p2.startswith("http"):
                            # 下载文件
                            if downloadFileFromUrl(p2, configFilePath) != 0:
                                await context.edit(f"下载配置文件异常,请确认url是否正确")
                                return
                            else:
                                # 下载成功,加载配置文件
                                redis.set(configFileRemoteUrlKey, p2)
                                if await loadConfigFile(context, True) != 0:
                                    await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确")
                                    return
                                else:
                                    await context.edit(f"下载并加载配置文件成功")
                        else:
                            # 根据传入模版id更新模版配置,多个用","或者","隔开
                            # 判断redis是否有保存配置url

                            splitStr = ","
                            if "," in p2:
                                splitStr = ","
                            ids = p2.split(splitStr)
                            if len(ids) > 0:
                                # 下载文件
                                configFileRemoteUrl = redis.get(configFileRemoteUrlKey)
                                if configFileRemoteUrl:
                                    if downloadFileFromUrl(configFileRemoteUrl, configFilePath) != 0:
                                        await context.edit(f"下载配置文件异常,请确认url是否正确")
                                        return
                                    else:
                                        # 下载成功,更新对应配置
                                        if await loadConfigFile(context) != 0:
                                            await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确")
                                            return
                                        else:
                                            await downloadFileByIds(ids, context)
                                else:
                                    await context.edit(f"你没有订阅远程配置文件,更新个🔨")
                    else:
                        # 没传url直接更新
                        if await updateConfig(context) != 0:
                            await context.edit(f"更新配置文件异常,请确认是否订阅远程配置文件,或从远程下载的配置文件格式是否正确")
                            return
                        else:
                            await context.edit(f"从远程更新配置文件成功")
                    return
                elif p1[0] == "!" or p1[0] == "!":
                    # 加载配置
                    if exists(configFilePath):
                        if await loadConfigFile(context) != 0:
                            await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确")
                            return
                    txt = ""
                    if len(positions) > 0:
                        noShowList = []
                        for key in positions:
                            txt = f"{txt},{key}"
                            if len(positions[key]) > 2:
                                noShowList.append(positions[key][2])
                        for key in noShowList:
                            txt = txt.replace(f",{key}", "")
                        if txt != "":
                            txt = txt[1:]
                    await context.edit(f"目前已有的模版列表如下:\n{txt}")
                    return
            defaultConfig = redis.get("eat.default-config")
            if isinstance(p2, str):
                number = p2
            elif isinstance(p2, int) and p2 > 0:
                number = int(p2)
            elif not diu_round and ((isinstance(p1, int) and int(p1) > 0) or isinstance(p1, str)):
                try:
                    number = int(p1)
                except:
                    number = p1
            elif defaultConfig:
                try:
                    defaultConfig = defaultConfig.decode()
                    number = int(defaultConfig)
                except:
                    number = str(defaultConfig)
                    # 支持配置默认是倒立的头像
                    if number.startswith("."):
                        diu_round = True
                        number = number[1:]

        except:
            number = randint(1, max_number)

        # 加载配置
        if exists(configFilePath):
            if await loadConfigFile(context) != 0:
                await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确")
                return

        try:
            notifyStr = notifyStrArr[str(number)]
        except:
            notifyStr = "吃头像"
        await context.edit(f"正在生成 {notifyStr} 图片中 . . .")
        markImg = Image.open("plugins/eat/" + str(target_user_id) + ".jpg")
        try:
            eatImg = Image.open("plugins/eat/eat" + str(number) + ".png")
            maskImg = Image.open("plugins/eat/mask" + str(number) + ".png")
        except:
            await context.edit(f"图片模版加载出错,请检查并更新配置:{str(number)}")
            return

        if diu_round:
            markImg = markImg.rotate(180)  # 对图片进行旋转
        try:
            number = str(number)
        except:
            pass
        result = await eat_it(context, from_user_id, eatImg, maskImg, markImg, number)
        result.save('plugins/eat/eat.webp')
        target_file = await context.client.upload_file("plugins/eat/eat.webp")
        try:
            remove("plugins/eat/" + str(target_user_id) + ".jpg")
            remove("plugins/eat/" + str(target_user_id) + ".png")
            remove("plugins/eat/" + str(from_user_id) + ".jpg")
            remove("plugins/eat/" + str(from_user_id) + ".png")
            remove("plugins/eat/eat.webp")
            remove(photo)
        except:
            pass
    else:
        await context.edit("此用户未设置头像或头像对您不可见。")
        return
    if reply_to:
        try:
            await context.client.send_file(
                context.chat_id,
                target_file,
                link_preview=False,
                force_document=False,
                reply_to=reply_to
            )
            await context.delete()
            remove("plugins/eat/eat.webp")
            try:
                remove(photo)
            except:
                pass
            return
        except TypeError:
            await context.edit("此用户未设置头像或头像对您不可见。")
        except ChatSendStickersForbiddenError:
            await context.edit("此群组无法发送贴纸。")
    else:
        try:
            await context.client.send_file(
                context.chat_id,
                target_file,
                link_preview=False,
                force_document=False
            )
            await context.delete()
            remove("plugins/eat/eat.webp")
            try:
                remove(photo)
            except:
                pass
            return
        except TypeError:
            await context.edit("此用户未设置头像或头像对您不可见。")
        except ChatSendStickersForbiddenError:
            await context.edit("此群组无法发送贴纸。")
Пример #25
0
async def reply_set(context):
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 离线,无法运行")
        await del_msg(context, 5)
        return
    chat_id = context.chat_id
    if chat_id > 0:
        await context.edit("请在群组中使用")
        await del_msg(context, 5)
        return
    params = context.parameter
    is_global = len(params) >= 1 and params[0] == "global"
    redis_data = "keyword.settings" if is_global else f"keyword.{chat_id}.settings"
    if is_global:
        del params[0]
    settings_dict = get_redis(redis_data)
    cmd_list = ["help", "mode", "list", "show", "clear"]
    cmd_dict = {
        "help": (1, ),
        "mode": (2, ),
        "list": (2, 3),
        "show": (1, ),
        "clear": (1, )
    }
    if len(params) < 1:
        await context.edit("参数错误")
        await del_msg(context, 5)
        return
    if params[0] in cmd_list and len(params) in cmd_dict[params[0]]:
        if params[0] == "help":
            await context.edit('''
`-replyset show` 或
`-replyset clear` 或
`-replyset mode <0/1/clear>` ( 0 表示黑名单,1 表示白名单 ) 或
`-replyset list <add/del/show/clear> [user_id]`。
在 `-replyset` 后面加上 `global` 即为全局设置''')
            await del_msg(context, 15)
            return
        elif params[0] == "show":
            defaults = {"mode": "未设置", "list": "未设置"}
            msg = "Settings: \n"
            for k, v in defaults.items():
                msg += f"`{k}` -> `{settings_dict[k] if k in settings_dict else v}`\n"
            await context.edit(msg)
            return
        elif params[0] == "mode":
            if params[1] in ("0", "1"):
                settings_dict["mode"] = params[1]
                redis.set(redis_data, save_rules(settings_dict, None))
                if params[1] == "0": await context.edit("模式已更改为黑名单")
                elif params[1] == "1": await context.edit("模式已更改为白名单")
                await del_msg(context, 5)
                return
            elif params[1] == "clear":
                if "mode" in settings_dict: del settings_dict["mode"]
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("清除成功")
                await del_msg(context, 5)
                return
            else:
                await context.edit("参数错误")
                await del_msg(context, 5)
                return
        elif params[0] == "list":
            if params[1] == "show" and len(params) == 2:
                user_list = settings_dict.get("list", None)
                if user_list:
                    msg = "List: \n"
                    for p in user_list.split(","):
                        msg += f"`{p}`\n"
                    await context.edit(msg)
                    return
                else:
                    await context.edit("列表为空")
                    await del_msg(context, 5)
                    return
            elif params[1] == "add" and len(params) == 3:
                if is_num(params[2]):
                    tmp = settings_dict.get("list", None)
                    if not tmp: settings_dict["list"] = params[2]
                    else: settings_dict["list"] += f",{params[2]}"
                    redis.set(redis_data, save_rules(settings_dict, None))
                    await context.edit("添加成功")
                    await del_msg(context, 5)
                    return
                else:
                    await context.edit("user_id 需为整数")
                    await del_msg(context, 5)
                    return
            elif params[1] == "del" and len(params) == 3:
                if is_num(params[2]):
                    tmp = settings_dict.get("list", None)
                    if tmp:
                        user_list = settings_dict["list"].split(",")
                        if params[2] in user_list:
                            user_list.remove(params[2])
                            settings_dict["list"] = ",".join(user_list)
                            redis.set(redis_data,
                                      save_rules(settings_dict, None))
                            await context.edit("删除成功")
                            await del_msg(context, 5)
                            return
                        else:
                            await context.edit("user_id 不在列表")
                            await del_msg(context, 5)
                            return
                    else:
                        await context.edit("列表为空")
                        await del_msg(context, 5)
                        return
                else:
                    await context.edit("user_id 需为整数")
                    await del_msg(context, 5)
                    return
            elif params[1] == "clear" and len(params) == 2:
                if "list" in settings_dict: del settings_dict["list"]
                redis.set(redis_data, save_rules(settings_dict, None))
                await context.edit("清除成功")
                await del_msg(context, 5)
                return
            else:
                await context.edit("参数错误")
                await del_msg(context, 5)
                return
        elif params[0] == "clear":
            redis.delete(redis_data)
            await context.edit("清除成功")
            await del_msg(context, 5)
            return
    else:
        await context.edit("参数错误")
        await del_msg(context, 5)
        return