⬆️ Update to Pyrogram v2

This commit is contained in:
xtaodada 2022-07-25 17:35:54 +08:00
parent f638883991
commit 9aebca7468
Signed by: xtaodada
GPG Key ID: 4CBB3F4FA8C85659
14 changed files with 75 additions and 91 deletions

2
.gitignore vendored
View File

@ -132,4 +132,4 @@ dmypy.json
# Pyre type checker # Pyre type checker
.pyre/ .pyre/
config.ini config.ini
bot.session bot.session*

View File

@ -4,10 +4,10 @@ from os.path import exists
def init() -> None: def init() -> None:
data = {}
if not exists("data"): if not exists("data"):
mkdir("data") mkdir("data")
if not exists(f"data{sep}anti_channel.pkl"): if not exists(f"data{sep}anti_channel.pkl"):
data = {}
with open(f"data{sep}anti_channel.pkl", "wb") as f: with open(f"data{sep}anti_channel.pkl", "wb") as f:
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
@ -46,14 +46,8 @@ def get(gid: int) -> list:
def get_status(gid: int) -> bool: def get_status(gid: int) -> bool:
if len(get(gid)) == 0: return len(get(gid)) != 0
return False
else:
return True
def check_status(gid: int, cid: int) -> bool: def check_status(gid: int, cid: int) -> bool:
if cid in get(gid): return cid in get(gid)
return True
else:
return False

View File

@ -6,8 +6,8 @@ from init import bot
async def how_many(message: str) -> str: async def how_many(message: str) -> str:
while re.findall("几|多少", message): while re.findall("几|多少", message):
message = message.replace("", str(secrets.choice(range(0, 99))), 1) message = message.replace("", str(secrets.choice(range(99))), 1)
message = message.replace("多少", str(secrets.choice(range(0, 99))), 1) message = message.replace("多少", str(secrets.choice(range(99))), 1)
return message return message
@ -22,12 +22,8 @@ async def what_time(message: str) -> str:
async def how_long(message: str) -> str: async def how_long(message: str) -> str:
unit = ["", "小时", "", "", "", "", "世纪"] unit = ["", "小时", "", "", "", "", "世纪"]
while re.findall("多久|多长时间", message): while re.findall("多久|多长时间", message):
message = message.replace( message = message.replace("多久", str(secrets.choice(range(99))) + secrets.choice(unit), 1)
"多久", str(secrets.choice(range(0, 99))) + secrets.choice(unit), 1 message = message.replace("多长时间", str(secrets.choice(range(99))) + secrets.choice(unit), 1)
)
message = message.replace(
"多长时间", str(secrets.choice(range(0, 99))) + secrets.choice(unit), 1
)
return message return message
@ -44,18 +40,16 @@ async def hif(message: str) -> str:
async def who(message: str, group_id: int) -> str: async def who(message: str, group_id: int) -> str:
group_member_list = await bot.get_chat_member(group_id) group_member_list = await bot.get_chat_member(group_id)
member_list: List[str] = [] member_list: List[str] = [n.first_name for n in group_member_list]
for n in group_member_list:
member_list += [n.first_name]
while "" in message: while "" in message:
member_name = member_list[secrets.choice(range(0, len(member_list) - 1))] member_name = member_list[secrets.choice(range(len(member_list) - 1))]
message = message.replace("", member_name, 1) message = message.replace("", member_name, 1)
return message return message
async def handle_pers(message: str) -> str: async def handle_pers(message: str) -> str:
message_list = list(message) message_list = list(message)
for i in range(0, len(message_list)): for i in range(len(message_list)):
if message_list[i] == "": if message_list[i] == "":
message_list[i] = "" message_list[i] = ""
continue continue

14
init.py
View File

@ -19,8 +19,12 @@ basicConfig(level=INFO)
logs.setLevel(INFO) logs.setLevel(INFO)
logger = logging.getLogger("iShotaBot") logger = logging.getLogger("iShotaBot")
# Init client # Init client
bot = Client("bot", ipv6=ipv6, plugins=dict(root="plugins"))
bot.start()
user_me = bot.get_me() class UserMe:
bot.stop() username = "iShotaBot"
bot = Client("bot", ipv6=ipv6) id = 2144128213
user_me = UserMe()
bot = Client("bot", ipv6=ipv6, plugins=dict(root="modules"))

View File

@ -1,3 +1,4 @@
import contextlib
from pyrogram import Client, filters, ContinuePropagation, errors from pyrogram import Client, filters, ContinuePropagation, errors
from pyrogram.types import Message from pyrogram.types import Message
from pyrogram.raw import types, functions from pyrogram.raw import types, functions
@ -12,7 +13,7 @@ init()
@Client.on_raw_update(filters.incoming & filters.group) @Client.on_raw_update(filters.incoming & filters.group)
async def anti_channel_msg(client: Client, update: Update, _, chats: dict): async def anti_channel_msg(client: Client, update: Update, _, __: dict):
while True: while True:
try: try:
# Check for message that are from channel # Check for message that are from channel
@ -41,7 +42,7 @@ async def anti_channel_msg(client: Client, update: Update, _, chats: dict):
raise ContinuePropagation raise ContinuePropagation
# Delete the message sent by channel and ban it. # Delete the message sent by channel and ban it.
await client.send( await client.invoke(
functions.channels.EditBanned( functions.channels.EditBanned(
channel=await client.resolve_peer(chat_id), channel=await client.resolve_peer(chat_id),
participant=await client.resolve_peer(channel_id), participant=await client.resolve_peer(channel_id),
@ -61,22 +62,17 @@ async def anti_channel_msg(client: Client, update: Update, _, chats: dict):
add(chat_id, channel_id) add(chat_id, channel_id)
raise ContinuePropagation raise ContinuePropagation
except errors.FloodWait as e: except errors.FloodWait as e:
logs.debug(f"{e}, retry after {e.x} seconds...") logs.debug(f"{e}, retry after {e.value} seconds...")
await sleep(e.x) await sleep(e.value)
except errors.ChatAdminRequired: except errors.ChatAdminRequired as e:
try: with contextlib.suppress(NameError):
clean(chat_id) # noqa clean(chat_id) # noqa
except NameError: raise ContinuePropagation from e
pass except ContinuePropagation as e:
raise ContinuePropagation raise ContinuePropagation from e
except ContinuePropagation:
raise ContinuePropagation
except: # noqa
logs.exception("An exception occurred in message_handler")
raise ContinuePropagation
@Client.on_message(filters.incoming & ~filters.edited & filters.group & @Client.on_message(filters.incoming & filters.group &
filters.command(["anti_channel_msg", f"anti_channel_msg@{user_me.username}"])) filters.command(["anti_channel_msg", f"anti_channel_msg@{user_me.username}"]))
async def switch_anti_channel_msg(client: Client, message: Message): async def switch_anti_channel_msg(client: Client, message: Message):
# Check user # Check user
@ -90,19 +86,8 @@ async def switch_anti_channel_msg(client: Client, message: Message):
if data.status not in ["creator", "administrator"]: if data.status not in ["creator", "administrator"]:
await message.reply("I'm not an admin of this chat.") await message.reply("I'm not an admin of this chat.")
raise ContinuePropagation raise ContinuePropagation
# Check if switch switch = len(message.text.split(" ")) > 1
switch = False if get_status(message.chat.id):
if len(message.text.split(" ")) > 1:
switch = True
if not get_status(message.chat.id):
if switch:
add(message.chat.id, message.chat.id)
await message.reply("Anti-channel is now enabled.")
else:
await message.reply("Anti-channel is already disabled.\n"
"\n"
"Tips: Use `/anti_channel_msg true` to enable or disable it.")
else:
if switch: if switch:
clean(message.chat.id) clean(message.chat.id)
await message.reply("Anti-channel is now disabled.") await message.reply("Anti-channel is now disabled.")
@ -110,4 +95,11 @@ async def switch_anti_channel_msg(client: Client, message: Message):
await message.reply("Anti-channel is already enabled.\n" await message.reply("Anti-channel is already enabled.\n"
"\n" "\n"
"Tips: Use `/anti_channel_msg true` to enable or disable it.") "Tips: Use `/anti_channel_msg true` to enable or disable it.")
elif switch:
add(message.chat.id, message.chat.id)
await message.reply("Anti-channel is now enabled.")
else:
await message.reply("Anti-channel is already disabled.\n"
"\n"
"Tips: Use `/anti_channel_msg true` to enable or disable it.")
raise ContinuePropagation raise ContinuePropagation

View File

@ -6,9 +6,9 @@ from pyrogram.types import Message
from defs.ask import how_many, what_time, how_long, hif, handle_pers, who from defs.ask import how_many, what_time, how_long, hif, handle_pers, who
@Client.on_message(filters.incoming & ~filters.edited & @Client.on_message(filters.incoming &
filters.regex(r"^问")) filters.regex(r"^问"))
async def ask(client: Client, message: Message): async def ask(_: Client, message: Message):
msg = message msg = message
if not message.text: if not message.text:
raise ContinuePropagation raise ContinuePropagation

View File

@ -1,13 +1,14 @@
import re import re
import random import random
from time import time
from datetime import datetime, timedelta
from pyrogram import Client, filters from pyrogram import Client, filters
from pyrogram.enums import ChatMemberStatus
from pyrogram.types import Message, ChatPermissions from pyrogram.types import Message, ChatPermissions
from init import user_me from init import user_me
@Client.on_message(filters.incoming & ~filters.edited & filters.group & @Client.on_message(filters.incoming & filters.group &
filters.command(["banme", f"banme@{user_me.username}"])) filters.command(["banme", f"banme@{user_me.username}"]))
async def ban_me_command(client: Client, message: Message): async def ban_me_command(client: Client, message: Message):
args = str(message.text).strip() args = str(message.text).strip()
@ -18,22 +19,24 @@ async def ban_me_command(client: Client, message: Message):
multiple = 1 multiple = 1
# 检查bot和用户身份 # 检查bot和用户身份
if not (await client.get_chat_member(message.chat.id, "self")).status == "administrator": if (await client.get_chat_member(message.chat.id, "self")).status != ChatMemberStatus.ADMINISTRATOR:
await message.reply('Bot非群管理员, 无法执行禁言操作QAQ') await message.reply('Bot非群管理员, 无法执行禁言操作QAQ')
return return
if not message.from_user: if not message.from_user:
# 频道 # 频道
await message.reply('也是个管理, 别来凑热闹OvO') await message.reply('是个频道, 别来凑热闹OvO')
return return
member = (await client.get_chat_member(message.chat.id, message.from_user.id)).status member = (await client.get_chat_member(message.chat.id, message.from_user.id)).status
if member in ["creator", "administrator"]: if member in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.OWNER]:
await message.reply('你也是个管理, 别来凑热闹OvO') await message.reply('你也是个管理, 别来凑热闹OvO')
return return
# 随机禁言时间 # 随机禁言时间
random_time = 2 * int(random.gauss(128 * multiple, 640 * multiple // 10)) random_time = 2 * int(random.gauss(128 * multiple, 640 * multiple // 10))
act_time = 60 if random_time < 60 else (random_time if random_time < 2591940 else 2591940) act_time = 60 if random_time < 60 else min(random_time, 2591940)
msg = f'既然你那么想被口球的话, 那我就成全你吧!\n送你一份{act_time // 60}{act_time % 60}秒禁言套餐哦, 谢谢惠顾~' msg = f'既然你那么想被口球的话, 那我就成全你吧!\n送你一份{act_time // 60}{act_time % 60}秒禁言套餐哦, 谢谢惠顾~'
await client.restrict_chat_member(message.chat.id, message.from_user.id, ChatPermissions(), int(time() + act_time)) await client.restrict_chat_member(message.chat.id, message.from_user.id, ChatPermissions(),
datetime.now() + timedelta(seconds=act_time))
await message.reply(msg) await message.reply(msg)

View File

@ -7,23 +7,20 @@ from defs.bilibili import b23_extract, video_info_get, binfo_image_create
from defs.button import gen_button, Button from defs.button import gen_button, Button
@Client.on_message(filters.incoming & ~filters.edited & @Client.on_message(filters.incoming &
filters.regex(r"av(\d{1,12})|BV(1[A-Za-z0-9]{2}4.1.7[A-Za-z0-9]{2})|b23.tv")) filters.regex(r"av(\d{1,12})|BV(1[A-Za-z0-9]{2}4.1.7[A-Za-z0-9]{2})|b23.tv"))
async def bili_resolve(client: Client, message: Message): async def bili_resolve(_: Client, message: Message):
""" """
解析 bilibili 链接 解析 bilibili 链接
""" """
video_info = None
if "b23.tv" in message.text: if "b23.tv" in message.text:
message.text = await b23_extract(message.text) message.text = await b23_extract(message.text)
p = re.compile(r"av(\d{1,12})|BV(1[A-Za-z0-9]{2}4.1.7[A-Za-z0-9]{2})") p = re.compile(r"av(\d{1,12})|BV(1[A-Za-z0-9]{2}4.1.7[A-Za-z0-9]{2})")
video_number = p.search(message.text) video_number = p.search(message.text)
if video_number: if video_number:
video_number = video_number.group(0) video_number = video_number[0]
if video_number: video_info = await video_info_get(video_number) if video_number else None
video_info = await video_info_get(video_number) if video_info and video_info["code"] == 0:
if video_info:
if video_info["code"] == 0:
image = binfo_image_create(video_info) image = binfo_image_create(video_info)
await message.reply_photo(image, await message.reply_photo(image,
quote=True, quote=True,

View File

@ -1,21 +1,22 @@
import json import json
from secrets import choice from secrets import choice
from os import sep from os import sep
from typing import List
from pyrogram import Client, filters, ContinuePropagation from pyrogram import Client, filters, ContinuePropagation
from pyrogram.types import Message from pyrogram.types import Message
book_of_answers: list[str] book_of_answers: List[str]
with open(f"resources{sep}text{sep}book_of_answers.json", "r", encoding="utf-8") as file: with open(f"resources{sep}text{sep}book_of_answers.json", "r", encoding="utf-8") as file:
book_of_answers = json.load(file) book_of_answers = json.load(file)
@Client.on_message(filters.incoming & ~filters.edited & @Client.on_message(filters.incoming &
filters.regex(r"^答案之书$")) filters.regex(r"^答案之书$"))
async def book_of_answer(client: Client, message: Message): async def book_of_answer(_: Client, message: Message):
await message.reply_text( await message.reply_text(
f"{choice(book_of_answers)}", f"{choice(book_of_answers)}",
quote=True quote=True

View File

@ -8,7 +8,7 @@ from pyrogram.types import Message
from defs.friend_say import ImageUtil from defs.friend_say import ImageUtil
@Client.on_message(filters.incoming & ~filters.edited & filters.group & @Client.on_message(filters.incoming & filters.group &
filters.regex(r"^我有个朋友")) filters.regex(r"^我有个朋友"))
async def friend_say(client: Client, message: Message): async def friend_say(client: Client, message: Message):
if not message.reply_to_message: if not message.reply_to_message:

View File

@ -1,14 +1,12 @@
from os import sep
from pyrogram import Client, filters, ContinuePropagation from pyrogram import Client, filters, ContinuePropagation
from pyrogram.types import Message from pyrogram.types import Message
from defs.luxun import process_pic from defs.luxun import process_pic
@Client.on_message(filters.incoming & ~filters.edited & @Client.on_message(filters.incoming &
filters.regex(r"^鲁迅说过")) filters.regex(r"^鲁迅说过"))
async def luxun_say(client: Client, message: Message): async def luxun_say(_: Client, message: Message):
args = message.text[4:] args = message.text[4:]
if not args: if not args:
await message.reply("烦了,不说了", quote=True) await message.reply("烦了,不说了", quote=True)

View File

@ -8,7 +8,7 @@ last_repeat_msg = {}
repeat_count = {} repeat_count = {}
@Client.on_message(filters.incoming & ~filters.edited & filters.group) @Client.on_message(filters.incoming & filters.group)
async def repeater_handler(client: Client, message: Message): async def repeater_handler(client: Client, message: Message):
global last_msg, last_repeat_msg, repeat_count global last_msg, last_repeat_msg, repeat_count

View File

@ -13,13 +13,14 @@ des = """本机器人特性:
""" """
@Client.on_message(filters.incoming & filters.private & ~filters.edited & @Client.on_message(filters.incoming & filters.private &
filters.command(["start"])) filters.command(["start"]))
async def start_command(client: Client, message: Message): async def start_command(_: Client, message: Message):
""" """
回应机器人信息 回应机器人信息
""" """
await message.reply(des, await message.reply(des,
quote=True, quote=True,
reply_markup=gen_button( reply_markup=gen_button(
[Button(0, "Gitlab", "https://gitlab.com/Xtao-Labs/iShotaBot")])) [Button(0, "Gitlab", "https://gitlab.com/Xtao-Labs/iShotaBot"),
Button(0, "Github", "https://github.com/Xtao-Labs/iShotaBot")]))

View File

@ -1,4 +1,4 @@
pyrogram pyrogram==2.0.35
tgcrypto tgcrypto
httpx httpx
pillow pillow