Exemplo n.º 1
0
from pagermaid.listener import listener
from pagermaid.utils import attach_log, execute, alias_command


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command("cal"),
          description="计算",
          parameters="<加减乘除>")
async def cal(context):
    command = context.arguments
    if context.is_channel and not context.is_group:
        await context.edit("`出错了呜呜呜 ~ 当前 PagerMaid-Modify 的配置禁止在频道中执行此命令。`")
        return

    if not command:
        await context.edit("`出错了呜呜呜 ~ 无效的参数。`")
        return

    await context.edit(f"{command}")
    cmd = f'echo "scale=4;{command}" | bc'
    result = await execute(cmd)

    if result:
        if len(result) > 4096:
            await attach_log(result, context.chat_id, "output.log", context.id)
            return

        await context.edit(f"{command}=\n`{result}`")
    else:
        return
Exemplo n.º 2
0
""" The help module. """

from os import listdir
from json import dump as json_dump
from pagermaid import help_messages, alias_dict, redis_status, redis, language
from pagermaid.utils import lang, alias_command
from pagermaid.listener import listener, config


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command("help"),
          description=lang('help_des'),
          parameters=f"<{lang('command')}>")
async def help_command(context):
    """ The help new command,"""
    support_commands = [
        'username', 'name', 'pfp', 'bio', 'rmpfp', 'profile', 'block',
        'unblock', 'ghost', 'deny', 'convert', 'caption', 'ocr', 'highlight',
        'time', 'translate', 'tts', 'google', 'animate', 'teletype', 'widen',
        'owo', 'flip', 'rng', 'aaa', 'tuxsay', 'coin', 'help', 'lang', 'alias',
        'id', 'uslog', 'log', 're', 'leave', 'hitokoto', 'apt', 'prune',
        'selfprune', 'yourprune', 'del', 'genqr', 'parseqr', 'sb', 'sysinfo',
        'status', 'stats', 'speedtest', 'connection', 'pingdc', 'ping',
        'topcloud', 's', 'sticker', 'sh', 'restart', 'trace', 'chat', 'update'
    ]
    if context.arguments:
        if context.arguments in help_messages:
            await context.edit(str(help_messages[context.arguments]))
        else:
            await context.edit(lang('arg_error'))
Exemplo n.º 3
0
import json, requests
from urllib.parse import quote
from pagermaid.listener import listener
from pagermaid.utils import alias_command, obtain_message, lang, clear_emojis


@listener(is_plugin=True,
          outgoing=True,
          command=alias_command("chatbot"),
          description="使用自然语言处理 (NLP) 来帮助用户通过文本进行交互。(支持回复)",
          parameters="<字符串>")
async def chatbot(context):
    try:
        text = await obtain_message(context)
    except ValueError:
        await context.edit(lang('msg_ValueError'))
        return
    text = clear_emojis(text)
    text = quote(text)

    try:
        req_data = requests.get(
            f"https://api.affiliateplus.xyz/api/chatbot?message={text}"
            f"&botname=pagermaid&ownername=xtao-labs&user=20")
    except Exception as e:
        await context.edit('出错了呜呜呜 ~ 无法访问 API ')
        return
    if not req_data.status_code == 200:
        return await context.edit('出错了呜呜呜 ~ 无法访问 API ')

    try:
Exemplo n.º 4
0
""" Module to automate sticker deletion. """
from asyncio import sleep
from pagermaid import log, version
from pagermaid.listener import listener
from pagermaid.utils import alias_command


@listener(is_plugin=True,
          outgoing=True,
          command=alias_command("fucksticker"),
          description="删除最近 50 条消息中的 sticker 。"
          "无管理员权限将只删除自己发送的 sticker 。")
async def fucksticker(context):
    """ Deletes specific amount of stickers in chat. """
    input_chat = await context.get_input_chat()
    count_buffer = 0
    count = 0
    messages = []
    async for message in context.client.iter_messages(context.chat_id):
        if count_buffer == 50:
            break
        if message.sticker:
            count += 1
            messages.append(message)
        else:
            pass
        count_buffer += 1
    text = f"删除了 {count} / {count_buffer} 条 sticker 。"
    try:
        await context.client.delete_messages(input_chat, messages)
    except Exception as e:
Exemplo n.º 5
0
""" PagerMaid module for adding captions to image. """

from os import remove
from magic import Magic
from pygments import highlight as syntax_highlight
from pygments.formatters import img
from pygments.lexers import guess_lexer
from pagermaid import log, module_dir
from pagermaid.listener import listener
from pagermaid.utils import execute, upload_attachment, lang, alias_command


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command("convert"),
          description=lang('convert_des'))
async def convert(context):
    """ Converts image to png. """
    reply = await context.get_reply_message()
    await context.edit(lang('convert_process'))
    target_file_path = await context.download_media()
    reply_id = context.reply_to_msg_id
    if reply:
        target_file_path = await context.client.download_media(
            await context.get_reply_message())
    if target_file_path is None:
        await context.edit(lang('convert_no_file'))
        return
    try:
        result = await execute(f"{module_dir}/assets/caption.sh \"" +
                               target_file_path + "\" result.png" + " \"" +
Exemplo n.º 6
0
""" PagerMaid module for channel help. """
from asyncio import sleep
from random import uniform
from telethon.errors.rpcerrorlist import FloodWaitError
from pagermaid import redis, log, redis_status, version
from pagermaid.utils import lang, alias_command
from pagermaid.listener import listener


@listener(
    is_plugin=False,
    outgoing=True,
    command=alias_command('shift'),
    description='开启转发频道新消息功能,需要 Redis',
    parameters="set <from channel> <to channel> 自动转发频道新消息(可以使用频道用户名或者 id)\n"
    "del <from channel> 删除转发\n"
    "backup <from channel> <to channel> 备份频道(可以使用频道用户名或者 id)")
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])
Exemplo n.º 7
0
import json
import sys, codecs

sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
from requests import get
from pagermaid import version
from pagermaid.listener import listener
from pagermaid.utils import obtain_message, alias_command


@listener(outgoing=True,
          command=alias_command("tel"),
          description="手机号码归属地等信息查询。")
async def tel(context):
    await context.edit("获取中 . . .")
    try:
        message = await obtain_message(context)
    except ValueError:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    req = get("https://tenapi.cn/tel?tel=" + message)
    if req.status_code == 200:
        data = json.loads(req.text)
        if not 'msg' in data:
            res = '电话号码:' + str(data['tel']) + '\n' + str(
                data['local']) + '\n' + str(data['duan']) + '\n' + str(
                    data['type']) + '\n' + str(data['yys']) + '\n' + str(
                        data['bz'])
        else:
            res = data['msg']
        await context.edit(res)
Exemplo n.º 8
0
from pagermaid import log, config, redis_status, start_time, silent
from pagermaid.utils import execute, upload_attachment, lang, alias_command
from pagermaid.listener import listener

DCs = {
    1: "149.154.175.50",
    2: "149.154.167.51",
    3: "149.154.175.100",
    4: "149.154.167.91",
    5: "91.108.56.130"
}


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command("sysinfo"),
          description=lang('sysinfo_des'))
async def sysinfo(context):
    """ Retrieve system information via neofetch. """
    if not silent:
        await context.edit(lang('sysinfo_loading'))
    result = await execute("neofetch --config none --stdout")
    await context.edit(f"`{result}`")


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command("fortune"),
          description=lang('fortune_des'))
async def fortune(context):
    """ Reads a fortune cookie. """
Exemplo n.º 9
0
""" Fun related chat utilities. """

from asyncio import sleep
from random import choice, random, randint, randrange, seed
from telethon.errors.rpcerrorlist import MessageNotModifiedError
from cowpy import cow
from pagermaid import module_dir
from pagermaid.listener import listener
from pagermaid.utils import owoify, execute, random_gen, obtain_message, lang, alias_command


@listener(is_plugin=False, outgoing=True, command=alias_command("animate"),
          description=lang('animate_des'),
          parameters="<message>")
async def animate(context):
    """ Make a text animation using a message. """
    try:
        message = await obtain_message(context)
    except ValueError:
        await context.edit(lang('arg_error'))
        return
    interval = 0.3
    words = message.split(" ")
    count = 0
    buffer = ""
    while count != len(words):
        await sleep(interval)
        buffer = f"{buffer} {words[count]}"
        try:
            await context.edit(buffer)
        except:
Exemplo n.º 10
0
from pagermaid.listener import listener
from pagermaid.utils import alias_command
from pagermaid import version


@listener(is_plugin=True, outgoing=True, command=alias_command("square"),
          description="生成文本矩形",
          parameters="<文本> <行> <列>")
async def square(context):
    if not len(context.parameter) > 2:
        await context.edit('出错了呜呜呜 ~ 参数错误。')
        return
    parameters = context.parameter[-2:]
    hang = parameters[0]
    lie = parameters[1]
    try:
        hang = int(hang)
        lie = int(lie)
    except ValueError:
        await context.edit('出错了呜呜呜 ~ 参数错误。')
        return
    if hang < 1 or lie < 1:
        await context.edit('出错了呜呜呜 ~ 参数错误。')
        return
    parameters = [i for i in context.parameter if i not in parameters]
    text = " ".join(parameters)
    text *=  lie
    text = text.strip()
    result = []
    for i in range(hang):
        result.append(text)
Exemplo n.º 11
0
""" Message related utilities. """

import requests
import json
from telethon.tl.functions.messages import DeleteChatUserRequest
from telethon.tl.functions.channels import LeaveChannelRequest, GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsAdmins
from telethon.errors.rpcerrorlist import ChatIdInvalidError
from distutils2.util import strtobool
from pagermaid import bot, log, config
from pagermaid.listener import listener
from pagermaid.utils import lang, alias_command


@listener(is_plugin=False, outgoing=True, command=alias_command("id"),
          description=lang('id_des'))
async def userid(context):
    """ Query the UserID of the sender of the message you replied to. """
    message = await context.get_reply_message()
    text = "Message ID: `" + str(context.message.id) + "`\n\n"
    text += "**Chat**\nid:`" + str(context.chat_id) + "`\n"
    msg_from = context.chat if context.chat else (await context.get_chat())
    if context.is_private:
        try:
            text += "first_name: `" + msg_from.first_name + "`\n"
        except TypeError:
            text += "**死号**\n"
        if msg_from.last_name:
            text += "last_name: `" + msg_from.last_name + "`\n"
        if msg_from.username:
            text += "username: @" + msg_from.username + "\n"
Exemplo n.º 12
0
""" PagerMaid features that uses external HTTP APIs other than Telegram. """

from os import remove
from magic_google import MagicGoogle
from gtts import gTTS
from gtts.tts import gTTSError
from re import compile as regex_compile

from pagermaid import log, silent
from pagermaid.listener import listener, config
from pagermaid.utils import clear_emojis, attach_log, fetch_youtube_audio, lang, alias_command


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command('translate'),
          description=lang('translate_des'),
          parameters=lang('translate_parameters'))
async def translate(context):
    """ PagerMaid universal translator. """
    reply = await context.get_reply_message()
    message = context.arguments
    ap_lang = config['application_language']
    if message:
        pass
    elif reply:
        message = reply.text
    else:
        await context.edit(lang('arg_error'))
        return
    source_text = clear_emojis(message)
Exemplo n.º 13
0
from pagermaid.listener import listener
from telethon import functions, types
from pagermaid.utils import alias_command
from pagermaid import version


@listener(outgoing=True,
          command=alias_command("nthmsg"),
          description="获取你发送的第 n 条消息,默认为第一条",
          parameters="<n>")
async def nthmsg(context):
    await context.edit("获取中 . . .")

    try:
        n = int(context.parameter[0])
    except:
        n = 1

    m = object()
    async for m in context.client.iter_messages(context.chat_id,
                                                from_user="******",
                                                reverse=True,
                                                limit=n):
        pass
    try:
        r = await context.client(
            functions.channels.ExportMessageLinkRequest(channel=m.to_id,
                                                        id=m.id,
                                                        grouped=True))
    except AttributeError:
        await context.edit('获取失败。')
Exemplo n.º 14
0
import json
from requests import get
from json.decoder import JSONDecodeError
from pagermaid.listener import listener
from pagermaid.utils import alias_command


@listener(is_plugin=True, outgoing=True, command=alias_command("zhrs"),
          description="知乎热搜。")
async def zhrs(context):
    await context.edit("获取中 . . .")
    req = get("https://tenapi.cn/zhihuresou")
    if req.status_code == 200:
        try:
            data = json.loads(req.text)
        except JSONDecodeError:
            await context.edit("出错了呜呜呜 ~ API 数据解析失败。")
            return
        res = '知乎实时热搜榜:\n'
        for i in range(0, 10):
            res += f'\n{i + 1}.「<a href={data["list"][i]["url"]}>{data["list"][i]["query"]}</a>」'
        await context.edit(res, parse_mode='html', link_preview=False)
    else:
        await context.edit("出错了呜呜呜 ~ 无法访问到 API 服务器 。")


@listener(is_plugin=True, outgoing=True, command=alias_command("wbrs"),
          description="微博热搜。")
async def wbrs(context):
    await context.edit("获取中 . . .")
    req = get("https://tenapi.cn/resou")
Exemplo n.º 15
0
        result = response.read()
        try:
            global CURRENCIES, DATA
            rate_data = xmltodict.parse(result)
            rate_data = rate_data['gesmes:Envelope']['Cube']['Cube']['Cube']
            for i in rate_data:
                CURRENCIES.append(i['@currency'])
                DATA[i['@currency']] = float(i['@rate'])
            CURRENCIES.sort()
        except Exception as e:
            raise e


@listener(is_plugin=True,
          outgoing=True,
          command=alias_command("bc"),
          description="coins",
          parameters="<num> <coin1> <coin2>")
async def coin(context: Message) -> None:
    """ coin change """
    if not imported:
        await context.edit(
            "支持库 `python-binance` `xmltodict` 未安装...\n正在尝试自动安装...")
        await execute(f'{executable} -m pip install python-binance')
        await execute(f'{executable} -m pip install xmltodict')
        await sleep(10)
        result = await execute(f'{executable} -m pip show python-binance')
        result1 = await execute(f'{executable} -m pip show xmltodict')
        if len(result) > 0 and len(result1) > 0:
            await context.edit(
                '支持库 `python-binance` `xmltodict` 安装成功...\n正在尝试自动重启...')
Exemplo n.º 16
0
import json
import requests
from json.decoder import JSONDecodeError
from pagermaid import version
from pagermaid.listener import listener
from pagermaid.utils import obtain_message, alias_command


@listener(is_plugin=True,
          outgoing=True,
          command=alias_command("bin"),
          description="查询信用卡信息",
          parameters="<bin(4到8位数字)>")
async def card(context):
    await context.edit('正在查询中...')
    try:
        card_bin = await obtain_message(context)
    except ValueError:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    try:
        r = requests.get("https://lookup.binlist.net/" + card_bin)
    except:
        await context.edit("出错了呜呜呜 ~ 无法访问到binlist。")
        return
    if r.status_code == 404:
        await context.edit("出错了呜呜呜 ~ 目标卡头不存在")
        return
    if r.status_code == 429:
        await context.edit("出错了呜呜呜 ~ 每分钟限额超过,请等待一分钟再试")
        return
Exemplo n.º 17
0
""" PagerMaid module to handle jd command. """

from pagermaid import version
from pagermaid.listener import listener
from pagermaid.utils import lang, alias_command, obtain_message, client


@listener(is_plugin=False, outgoing=True, command=alias_command("jd_cmd"),
          description="解析 JD 口令",
          parameters="<JD 口令>")
async def jd_cmd(context):
    try:
        text = await obtain_message(context)
    except ValueError:
        return await context.edit("[jd_cmd] " + lang("msg_ValueError"))
    try:
        data = (await client.post("https://api.jds.codes/jd/jCommand", json={"code": text})).json()
    except:
        return await context.edit("[jd_cmd] 网络错误!")
    if data["code"] != 200:
        return await context.edit("[jd_cmd] 未找到 JD 口令!")
    try:
        data = data["data"]
        await context.edit(f"【jd_cmd】 [【{data['title']}】 - {data['userName']}]({data['jumpUrl']})")
    except KeyError:
        return await context.edit("[jd_cmd] 数据错误!")
Exemplo n.º 18
0
from io import BytesIO
from telethon.tl.types import DocumentAttributeFilename, MessageMediaPhoto, MessageMediaWebPage, MessageMediaDice, \
    MessageMediaUnsupported
from telethon.tl.functions.contacts import UnblockRequest
from telethon.errors.common import AlreadyInConversationError
from PIL import Image, ImageOps
from math import floor
from pagermaid import bot, redis, redis_status, silent
from pagermaid.listener import listener
from pagermaid.utils import lang, alias_command, get
from pagermaid import log


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command("s"),
          description=lang('sticker_des'),
          parameters="<emoji>")
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"):
Exemplo n.º 19
0
from pathlib import Path
from pagermaid import log, config, redis_status, start_time
from pagermaid.utils import execute
from pagermaid.listener import listener
from pagermaid.utils import lang, alias_command, get

DCs = {
    1: "149.154.175.50",
    2: "149.154.167.51",
    3: "149.154.175.100",
    4: "149.154.167.91",
    5: "91.108.56.130"
}


@listener(is_plugin=False, incoming=True, owners_only=True, command=alias_command("sysinfo"),
          description=lang('sysinfo_des'))
async def sysinfo(context):
    """ Retrieve system information via neofetch. """
    msg = await context.reply(lang('sysinfo_loading'))
    result = await execute("neofetch --config none --stdout")
    await msg.edit(f"`{result}`")


@listener(is_plugin=False, incoming=True, owners_only=True, command=alias_command("status"),
          description=lang('status_des'))
async def status(context):
    # database
    database = lang('status_online') if redis_status() else lang('status_offline')
    # uptime https://gist.github.com/borgstrom/936ca741e885a1438c374824efb038b3
    time_units = (
Exemplo n.º 20
0
from time import sleep
from os.path import exists
from os import mkdir, remove
from pagermaid import version
from pagermaid.utils import alias_command
from pagermaid.listener import listener


@listener(is_plugin=True,
          outgoing=True,
          command=alias_command("aff"),
          description="在别人要打算买机场的时候光速发出自己的aff信息(请尽量配合短链接)",
          parameters="<save|remove> (可选,用于保存|删除aff信息)")
async def aff(context):
    if not context.parameter:  # 发送aff信息
        try:
            with open("plugins/AffExtra/aff.txt", "r", encoding="UTF-8") as f:
                msg = f.read()
        except:
            msg = ""
        if msg == "":
            await context.edit("出错了呜呜呜 ~ Aff消息不存在。\n(你有提前保存好嘛?)")
            return
        try:
            await context.edit(msg, link_preview=True)
        except:
            await context.edit("出错了呜呜呜 ~ 信息无变化。")
            sleep(3)
            await context.delete()
    elif context.parameter[0] == "save":  # 保存aff信息
        reply = await context.get_reply_message()
Exemplo n.º 21
0
    else:
        time = f"{sec}秒"
    return time


def mention_user(user):
    if user.username:
        mention = user.username
    else:
        mention = user.id
    return f'`{user.first_name}` [`{mention}`]'


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command("fuckadmin"),
          description='列出群组中所有潜水超过 n 天的管理员。(n>=7)。',
          parameters="<day>")
async def fuck_admin(context):
    admins = 0
    if context.is_group:
        pass
    else:
        await context.edit('请在群组中运行。')
        return
    # 读取天数
    text = ''
    if len(context.parameter) == 1:
        try:
            day = int(context.parameter[0])
            if day < 7:
Exemplo n.º 22
0
from os import remove
from subprocess import run, PIPE
from sys import executable

from git import Repo
from git.exc import GitCommandError, InvalidGitRepositoryError, NoSuchPathError

from pagermaid import log
from pagermaid.listener import listener
from pagermaid.utils import execute, lang, alias_command


@listener(is_plugin=False,
          incoming=True,
          owners_only=True,
          command=alias_command("update"),
          description=lang('update_des'),
          parameters="<true/debug>")
async def update(context):
    if len(context.parameter) > 1:
        await context.reply(lang('arg_error'))
        return
    msg = await context.reply(lang('update_processing'))
    parameter = None
    changelog = None
    if len(context.parameter) == 1:
        parameter = context.parameter[0]

    if parameter:
        if parameter == "debug":
            # Version info
Exemplo n.º 23
0
""" PagerMaid module for different ways to avoid users. """

from pagermaid import redis, log, redis_status
from pagermaid.utils import lang, alias_command
from pagermaid.listener import listener


@listener(is_plugin=False, outgoing=True, command=alias_command('ghost'),
          description=lang('ghost_des'),
          parameters="<true|false|status>")
async def ghost(context):
    """ Toggles ghosting 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("ghosted.chat_id." + str(context.chat_id), "true")
        await context.delete()
        await log(f"{lang('ghost_set_f')} ChatID {str(context.chat_id)} {lang('ghost_set_l')}")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
Exemplo n.º 24
0
import random
from requests import get
from pagermaid import version
from pagermaid.listener import listener
from pagermaid.utils import alias_command
from os import remove


@listener(is_plugin=True,
          outgoing=True,
          command=alias_command("mz"),
          description="多网站随机获取性感(可能)的写真")
async def mz(context):
    await context.edit("获取中 . . .")
    status = False
    for _ in range(20):  # 最多重试20次
        website = random.randint(0, 13)
        filename = "mz" + str(random.random())[2:] + ".png"
        try:
            if website == 0:
                img = get("https://mm.52.mk/img")
            elif website == 1:
                img = get("https://api.helloworld.la/xiezhen_xinggan.php")
            elif website == 2:
                img = get("https://api.66mz8.com/api/rand.tbimg.php")
            elif website == 3:
                img = get("https://api.nmb.show/xiaojiejie2.php")
            elif website == 4:
                img = get(
                    "https://uploadbeta.com/api/pictures/random/?key=%E5%A5%B3"
                )
Exemplo n.º 25
0
from telethon.errors.rpcerrorlist import PhotoExtInvalidError, UsernameOccupiedError, AboutTooLongError, \
    FirstNameInvalidError, UsernameInvalidError, UsernameNotModifiedError
from telethon.tl.functions.account import UpdateProfileRequest, UpdateUsernameRequest
from telethon.tl.functions.photos import DeletePhotosRequest, GetUserPhotosRequest, UploadProfilePhotoRequest
from telethon.tl.functions.users import GetFullUserRequest
from telethon.tl.functions.contacts import BlockRequest, UnblockRequest
from telethon.tl.types import InputPhoto, MessageMediaPhoto, MessageEntityMentionName, MessageEntityPhone, User
from struct import error as StructError
from pagermaid import bot, log, silent
from pagermaid.utils import lang, alias_command
from pagermaid.listener import listener


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command('username'),
          description=lang('username_des'),
          parameters="<username>")
async def username(context):
    """ Reconfigure your username. """
    if len(context.parameter) > 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}}")
    if len(context.parameter) == 1:
        result = context.parameter[0]
    else:
        result = ""
    try:
        await bot(UpdateUsernameRequest(result))
    except UsernameOccupiedError:
        await context.edit(f"{lang('error_prefix')}{lang('username_exist')}")
        return
Exemplo n.º 26
0
""" Module to automate message deletion. """
from asyncio import sleep
from os import path, remove
from os.path import exists
from PIL import Image, UnidentifiedImageError
from pagermaid import redis, log, redis_status
from pagermaid.listener import listener
from pagermaid.utils import alias_command


@listener(is_plugin=True,
          outgoing=True,
          command=alias_command("dme"),
          description="编辑并删除当前对话您发送的特定数量的消息。限制:基于消息 ID 的 1000 条消息,大于 1000 "
          "条可能会触发删除消息过快限制。入群消息非管理员无法删除。(倒序)当数字足够大时即可实现删除所有消息。",
          parameters="<数量> [文本]")
async def dme(context):
    """ Deletes specific amount of messages you sent. """
    reply = await context.get_reply_message()
    if reply and reply.photo:
        if exists('plugins/dme.jpg'):
            remove('plugins/dme.jpg')
        target_file = reply.photo
        await context.client.download_media(await context.get_reply_message(),
                                            file="plugins/dme.jpg")
        await context.edit("替换图片设置完成。")
    elif reply and reply.sticker:
        if exists('plugins/dme.jpg'):
            remove('plugins/dme.jpg')
        await context.client.download_media(reply.media.document,
                                            file="plugins/dme.webp")
Exemplo n.º 27
0
    try:
        if chat.username:
            if chat.username:
                text = f'[{chat.title}](https://t.me/{chat.username})'
            else:
                text = f'`{chat.title}`'
        else:
            text = f'`{chat.title}`'
    except AttributeError:
        text = f'`{chat.title}`'
    return text


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command("sb"),
          description=lang('sb_des'),
          parameters="<reply|id|username> <do_not_del_all>")
async def span_ban(context):
    if context.reply_to_msg_id:
        reply_message = await context.get_reply_message()
        if reply_message:
            try:
                user = reply_message.from_id
            except AttributeError:
                await context.edit(lang('arg_error'))
                return
        else:
            await context.edit(lang('arg_error'))
            return
        if isinstance(user, PeerChannel):
Exemplo n.º 28
0
    mask1 = Image.new('RGBA', mask_size)
    mask1.paste(photo, mask=mask)
    base.paste(mask1, (positions[str(number)][0], positions[str(number)][1]),
               mask1)
    temp = base.size[0] if base.size[0] > base.size[1] else base.size[1]
    if temp != 512:
        scale = 512 / temp
        base = base.resize(
            (int(base.size[0] * scale), int(base.size[1] * scale)),
            Image.LANCZOS)
    return base


@listener(is_plugin=True,
          outgoing=True,
          command=alias_command("eat"),
          description="生成一张 吃头像 图片,(可选:当第二个参数存在时,旋转用户头像 180°)",
          parameters="<username/uid> [随意内容]")
async def eat(context):
    if len(context.parameter) > 2:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    diu_round = False
    await context.edit("正在生成 吃头像 图片中 . . .")
    if context.reply_to_msg_id:
        reply_message = await context.get_reply_message()
        user_id = reply_message.sender_id
        target_user = await context.client(GetFullUserRequest(user_id))
        if len(context.parameter) == 1:
            diu_round = True
    else:
Exemplo n.º 29
0
import random
from requests import get
from pagermaid import version
from pagermaid.listener import listener
from pagermaid.utils import alias_command
from os import remove


@listener(is_plugin=True,
          outgoing=True,
          command=alias_command("xjj"),
          description="随机小姐姐写真")
async def ghs(context):
    await context.edit("拍小姐姐写真中 . . .")
    status = False
    for _ in range(10):  # 最多重试10次
        website = random.randint(0, 0)
        filename = "xjj" + str(random.random())[2:] + ".png"
        try:
            if website == 0:
                img = get("https://acg.toubiec.cn/random.php")
            if img.status_code == 200:
                with open(filename, 'wb') as f:
                    f.write(img.content)
                await context.edit("写真我拍好辣,上传中 . . .")
                await context.client.send_file(
                    context.chat_id,
                    filename,
                    caption="小姐姐来辣~⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄)")
                status = True
                break  # 成功了就赶紧结束啦!
Exemplo n.º 30
0
""" PagerMaid module to handle sticker collection. """

from io import BytesIO
from telethon.tl.types import DocumentAttributeFilename, MessageMediaPhoto, MessageMediaWebPage
from PIL import Image, ImageOps
from math import floor
from pagermaid import bot, redis, redis_status
from pagermaid.listener import listener
from pagermaid.utils import lang, alias_command


@listener(is_plugin=False,
          outgoing=True,
          command=alias_command("pic2sticker"),
          description='将图片转换为贴纸',
          parameters="<round>")
async def pic2sticker(context):
    """ Fetches images and send it as sticker. """
    pic_round = False
    if len(context.parameter) >= 1:
        pic_round = True

    if redis_status():
        if redis.get("sticker.round"):
            pic_round = True

    message = await context.get_reply_message()
    if message and message.media:
        if isinstance(message.media, MessageMediaPhoto):
            photo = BytesIO()
            photo = await bot.download_media(message.photo, photo)