支持 Inline Query MiYouShe Splash

This commit is contained in:
xtaodada 2023-06-23 23:37:55 +08:00
parent c90c7c41c2
commit 1d4c269bda
Signed by: xtaodada
GPG Key ID: 4CBB3F4FA8C85659
22 changed files with 133 additions and 69 deletions

View File

@ -4,6 +4,7 @@ from typing import List
from pyrogram.enums import ParseMode from pyrogram.enums import ParseMode
from pyrogram.errors import FloodWait from pyrogram.errors import FloodWait
from pyrogram.types import InlineQueryResultCachedPhoto
from defs.glover import splash_channel from defs.glover import splash_channel
from init import bot, request, logger from init import bot, request, logger
@ -113,3 +114,18 @@ async def update_splash():
continue continue
await SplashService.add_splash(model) await SplashService.add_splash(model)
logger.info("Splash updated.") logger.info("Splash updated.")
async def get_inline_results() -> List[InlineQueryResultCachedPhoto]:
splash = await SplashService.get_all_splashes()
splash.sort(key=lambda x: x.offline_ts, reverse=True)
splash = splash[:50]
results = []
for idx, i in enumerate(splash):
results.append(
InlineQueryResultCachedPhoto(
title=f"Splash No.{idx + 1}",
photo_file_id=i.file_id,
)
)
return results

10
init.py
View File

@ -21,6 +21,9 @@ logging_handler.setFormatter(ColoredFormatter(logging_format))
root_logger = getLogger() root_logger = getLogger()
root_logger.setLevel(ERROR) root_logger.setLevel(ERROR)
root_logger.addHandler(logging_handler) root_logger.addHandler(logging_handler)
# pyro_logger = getLogger()
# pyro_logger.setLevel(INFO)
# pyro_logger.addHandler(logging_handler)
basicConfig(level=INFO) basicConfig(level=INFO)
logs.setLevel(INFO) logs.setLevel(INFO)
logger = logging.getLogger("iShotaBot") logger = logging.getLogger("iShotaBot")
@ -29,13 +32,6 @@ if not scheduler.running:
scheduler.start() scheduler.start()
# Init client # Init client
class UserMe:
username = "iShotaBot"
id = 2144128213
user_me = UserMe()
sqlite = Sqlite() sqlite = Sqlite()
bot = pyrogram.Client( bot = pyrogram.Client(
"bot", api_id=api_id, api_hash=api_hash, ipv6=ipv6, plugins=dict(root="modules") "bot", api_id=api_id, api_hash=api_hash, ipv6=ipv6, plugins=dict(root="modules")

22
main.py
View File

@ -1,13 +1,19 @@
import asyncio
from pyrogram import idle from pyrogram import idle
from init import logs, user_me, bot, sqlite from init import logs, bot, sqlite
async def main():
logs.info("连接服务器中。。。")
await bot.start()
bot.loop.create_task(sqlite.create_db_and_tables())
logs.info(f"@{bot.me.username} 运行成功!")
await idle()
await bot.stop()
sqlite.stop()
if __name__ == "__main__": if __name__ == "__main__":
logs.info(f"@{user_me.username} 连接服务器中。。。") asyncio.get_event_loop().run_until_complete(main())
bot.start()
bot.loop.create_task(sqlite.create_db_and_tables())
logs.info(f"@{user_me.username} 运行成功!")
idle()
bot.stop()
sqlite.stop()

View File

@ -8,12 +8,12 @@ from pyrogram.raw.base import Update
from asyncio import sleep from asyncio import sleep
from defs.anti_channel import init, add, get_status, check_status, clean from defs.anti_channel import init, add, get_status, check_status, clean
from init import logs, user_me from init import logs, bot
init() init()
@Client.on_raw_update(filters.incoming & filters.group) @bot.on_raw_update(filters.incoming & filters.group)
async def anti_channel_msg(client: Client, update: Update, _, __: dict): async def anti_channel_msg(client: Client, update: Update, _, __: dict):
while True: while True:
try: try:
@ -77,10 +77,10 @@ async def anti_channel_msg(client: Client, update: Update, _, __: dict):
raise ContinuePropagation from e raise ContinuePropagation from e
@Client.on_message( @bot.on_message(
filters.incoming filters.incoming
& filters.group & filters.group
& filters.command(["anti_channel_msg", f"anti_channel_msg@{user_me.username}"]) & filters.command(["anti_channel_msg", f"anti_channel_msg@{bot.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,7 +90,7 @@ async def switch_anti_channel_msg(client: Client, message: Message):
await message.reply("You are not an admin of this chat.") await message.reply("You are not an admin of this chat.")
raise ContinuePropagation raise ContinuePropagation
# Check self # Check self
data = await client.get_chat_member(message.chat.id, user_me.id) data = await client.get_chat_member(message.chat.id, bot.me.id)
if data.status not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.OWNER]: if data.status not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.OWNER]:
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

View File

@ -3,10 +3,11 @@ import re
from pyrogram import Client, filters, ContinuePropagation from pyrogram import Client, filters, ContinuePropagation
from pyrogram.types import Message from pyrogram.types import Message
from init import bot
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.regex(r"^问")) @bot.on_message(filters.incoming & filters.regex(r"^问"))
async def ask(_: Client, message: Message): async def ask(_: Client, message: Message):
msg = message msg = message
if not message.text: if not message.text:

View File

@ -6,7 +6,7 @@ from datetime import datetime, timedelta
from pyrogram import Client, filters from pyrogram import Client, filters
from pyrogram.enums import ChatMemberStatus from pyrogram.enums import ChatMemberStatus
from pyrogram.types import Message, ChatPermissions, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton from pyrogram.types import Message, ChatPermissions, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
from init import user_me from init import bot
from scheduler import reply_message from scheduler import reply_message
@ -20,10 +20,10 @@ def gen_cancel_button(uid: int):
) )
@Client.on_message( @bot.on_message(
filters.incoming filters.incoming
& filters.group & filters.group
& filters.command(["banme", f"banme@{user_me.username}"]) & filters.command(["banme", f"banme@{bot.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()
@ -67,7 +67,7 @@ async def ban_me_command(client: Client, message: Message):
await reply_message(message, msg, reply_markup=gen_cancel_button(message.from_user.id)) await reply_message(message, msg, reply_markup=gen_cancel_button(message.from_user.id))
@Client.on_callback_query( @bot.on_callback_query(
filters.regex(r"^banme_cancel_(\d+)$") filters.regex(r"^banme_cancel_(\d+)$")
) )
async def ban_me_cancel(client: Client, callback_query: CallbackQuery): async def ban_me_cancel(client: Client, callback_query: CallbackQuery):

View File

@ -11,9 +11,10 @@ from defs.bilibili import (
get_dynamic_screenshot_pc, get_dynamic_screenshot_pc,
) )
from defs.button import gen_button, Button from defs.button import gen_button, Button
from init import bot
@Client.on_message( @bot.on_message(
filters.incoming filters.incoming
& filters.text & filters.text
& 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")
@ -41,7 +42,7 @@ async def bili_resolve(_: Client, message: Message):
raise ContinuePropagation raise ContinuePropagation
@Client.on_message( @bot.on_message(
filters.incoming & filters.text & filters.regex(r"t.bilibili.com/([0-9]*)") filters.incoming & filters.text & filters.regex(r"t.bilibili.com/([0-9]*)")
) )
async def bili_dynamic(_: Client, message: Message): async def bili_dynamic(_: Client, message: Message):

View File

@ -6,6 +6,7 @@ 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
from init import bot
book_of_answers: List[str] book_of_answers: List[str]
@ -16,7 +17,7 @@ with open(
book_of_answers = json.load(file) book_of_answers = json.load(file)
@Client.on_message(filters.incoming & filters.regex(r"^答案之书$")) @bot.on_message(filters.incoming & filters.regex(r"^答案之书$"))
async def book_of_answer(_: Client, message: Message): async def book_of_answer(_: Client, message: Message):
await message.reply_text(f"{choice(book_of_answers)}", quote=True) await message.reply_text(f"{choice(book_of_answers)}", quote=True)
raise ContinuePropagation raise ContinuePropagation

View File

@ -1,7 +1,7 @@
from pyrogram import Client, filters from pyrogram import Client, filters
from pyrogram.types import Message, Chat from pyrogram.types import Message, Chat
from init import user_me from init import bot
def mention_chat(chat: Chat) -> str: def mention_chat(chat: Chat) -> str:
@ -31,7 +31,7 @@ def get_dc(message: Message):
return dc, mention return dc, mention
@Client.on_message(filters.incoming & filters.command(["dc", f"dc@{user_me.username}"])) @bot.on_message(filters.incoming & filters.command(["dc", f"dc@{bot.me.username}"]))
async def dc_command(_: Client, message: Message): async def dc_command(_: Client, message: Message):
geo_dic = { geo_dic = {
"1": "美国-佛罗里达州-迈阿密", "1": "美国-佛罗里达州-迈阿密",

View File

@ -4,7 +4,7 @@ from pyrogram.types import Message
from defs.exchange import exchange_client from defs.exchange import exchange_client
from scheduler import scheduler from scheduler import scheduler
from init import user_me from init import bot
@scheduler.scheduled_job("cron", hour="8", id="exchange.refresh") @scheduler.scheduled_job("cron", hour="8", id="exchange.refresh")
@ -12,8 +12,8 @@ async def exchange_refresh() -> None:
await exchange_client.refresh() await exchange_client.refresh()
@Client.on_message( @bot.on_message(
filters.incoming & filters.command(["exchange", f"exchange@{user_me.username}"]) filters.incoming & filters.command(["exchange", f"exchange@{bot.me.username}"])
) )
async def exchange_command(_: Client, message: Message): async def exchange_command(_: Client, message: Message):
if not exchange_client.inited: if not exchange_client.inited:

View File

@ -3,9 +3,10 @@ from pyrogram.enums import MessageEntityType
from pyrogram.types import Message from pyrogram.types import Message
from defs.fanbox import parse_fanbox_url from defs.fanbox import parse_fanbox_url
from init import bot
@Client.on_message(filters.incoming & filters.text & filters.regex(r"fanbox.cc")) @bot.on_message(filters.incoming & filters.text & filters.regex(r"fanbox.cc"))
async def fanbox_check(_: Client, message: Message): async def fanbox_check(_: Client, message: Message):
if not message.text: if not message.text:
return return

View File

@ -14,14 +14,14 @@ from pyrogram.types import (
from models.fragment import FragmentSubText, FragmentSub, AuctionStatus from models.fragment import FragmentSubText, FragmentSub, AuctionStatus
from defs.fragment import parse_fragment, NotAvailable, parse_sub from defs.fragment import parse_fragment, NotAvailable, parse_sub
from init import user_me, bot from init import bot
from scheduler import scheduler, add_delete_message_job from scheduler import scheduler, add_delete_message_job
QUERY_PATTERN = re.compile(r"^@\w[a-zA-Z0-9_]{3,32}$") QUERY_PATTERN = re.compile(r"^@\w[a-zA-Z0-9_]{3,32}$")
@Client.on_message( @bot.on_message(
filters.incoming & filters.command(["username", f"username@{user_me.username}"]) filters.incoming & filters.command(["username", f"username@{bot.me.username}"])
) )
async def fragment_command(client: Client, message: Message): async def fragment_command(client: Client, message: Message):
status = None status = None
@ -61,18 +61,9 @@ async def fragment_command(client: Client, message: Message):
await message.reply(text) await message.reply(text)
@Client.on_inline_query() @bot.on_inline_query(filters=filters.regex(r"^@\w[a-zA-Z0-9_]{3,32}$"))
async def fragment_inline(_, inline_query: InlineQuery): async def fragment_inline(_, inline_query: InlineQuery):
username = inline_query.query username = inline_query.query
if not username.startswith("@"):
username = f"@{username}"
if not QUERY_PATTERN.match(username):
return await inline_query.answer(
results=[],
switch_pm_text="请输入 @username 来查询遗产",
switch_pm_parameter="start",
cache_time=0,
)
username = username[1:] username = username[1:]
try: try:
user = await parse_fragment(username) user = await parse_fragment(username)
@ -82,12 +73,13 @@ async def fragment_inline(_, inline_query: InlineQuery):
except Exception: except Exception:
text = "" text = ""
if not text: if not text:
return await inline_query.answer( await inline_query.answer(
results=[], results=[],
switch_pm_text="查询失败了 ~ 呜呜呜", switch_pm_text="查询失败了 ~ 呜呜呜",
switch_pm_parameter="start", switch_pm_parameter="start",
cache_time=0, cache_time=0,
) )
inline_query.stop_propagation()
results = [ results = [
InlineQueryResultArticle( InlineQueryResultArticle(
title=username, title=username,
@ -111,6 +103,7 @@ async def fragment_inline(_, inline_query: InlineQuery):
switch_pm_parameter="start", switch_pm_parameter="start",
cache_time=0, cache_time=0,
) )
inline_query.stop_propagation()
@scheduler.scheduled_job("cron", hour="8", minute="1", id="fragment.sub") @scheduler.scheduled_job("cron", hour="8", minute="1", id="fragment.sub")

View File

@ -6,9 +6,10 @@ from pyrogram import Client, filters, ContinuePropagation
from pyrogram.types import Message from pyrogram.types import Message
from defs.friend_say import ImageUtil from defs.friend_say import ImageUtil
from init import bot
@Client.on_message(filters.incoming & filters.group & filters.regex(r"^我有个朋友")) @bot.on_message(filters.incoming & filters.group & 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:
raise ContinuePropagation raise ContinuePropagation

View File

@ -1,19 +1,17 @@
import contextlib import contextlib
from urllib.parse import quote from urllib.parse import quote
from pyrogram import Client, filters from pyrogram import Client, filters
from pyrogram.types import Message from pyrogram.types import Message
from defs.glover import amap_key from defs.glover import amap_key
from init import request, bot
from init import user_me, request
REQUEST_URL = f"https://restapi.amap.com/v3/geocode/geo?key={amap_key}&" REQUEST_URL = f"https://restapi.amap.com/v3/geocode/geo?key={amap_key}&"
@Client.on_message( @bot.on_message(
filters.incoming & filters.command(["geo", f"geo@{user_me.username}"]) filters.incoming & filters.command(["geo", f"geo@{bot.me.username}"])
) )
async def geo_command(_: Client, message: Message): async def geo_command(_: Client, message: Message):
if len(message.command) <= 1: if len(message.command) <= 1:

View File

@ -2,11 +2,11 @@ from pyrogram import Client, filters
from pyrogram.types import Message from pyrogram.types import Message
from defs.guess import guess_str from defs.guess import guess_str
from init import user_me from init import bot
@Client.on_message( @bot.on_message(
filters.incoming & filters.command(["guess", f"guess@{user_me.username}"]) filters.incoming & filters.command(["guess", f"guess@{bot.me.username}"])
) )
async def guess_command(_: Client, message: Message): async def guess_command(_: Client, message: Message):
msg = await message.reply("正在查询中...") msg = await message.reply("正在查询中...")

View File

@ -4,10 +4,10 @@ from pyrogram import Client, filters
from pyrogram.types import Message from pyrogram.types import Message
from defs.ip import ip_info from defs.ip import ip_info
from init import user_me, request from init import request, bot
@Client.on_message(filters.incoming & filters.command(["ip", f"ip@{user_me.username}"])) @bot.on_message(filters.incoming & filters.command(["ip", f"ip@{bot.me.username}"]))
async def ip_command(_: Client, message: Message): async def ip_command(_: Client, message: Message):
msg = await message.reply("正在查询中...") msg = await message.reply("正在查询中...")
rep_text = "" rep_text = ""

View File

@ -3,9 +3,10 @@ from pyrogram.enums import MessageEntityType
from pyrogram.types import Message from pyrogram.types import Message
from defs.lofter import get_loft, input_media, get_loft_user, lofter_user_link from defs.lofter import get_loft, input_media, get_loft_user, lofter_user_link
from init import bot
@Client.on_message(filters.incoming & filters.text & filters.regex(r"lofter.com")) @bot.on_message(filters.incoming & filters.text & filters.regex(r"lofter.com"))
async def lofter_share(_: Client, message: Message): async def lofter_share(_: Client, message: Message):
if not message.text: if not message.text:
return return

View File

@ -2,9 +2,10 @@ 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
from init import bot
@Client.on_message(filters.incoming & filters.regex(r"^鲁迅说过")) @bot.on_message(filters.incoming & filters.regex(r"^鲁迅说过"))
async def luxun_say(_: Client, message: Message): async def luxun_say(_: Client, message: Message):
args = message.text[4:] args = message.text[4:]
if not args: if not args:

View File

@ -3,9 +3,10 @@ from defs.glover import admin
from pyrogram.types import Message from pyrogram.types import Message
from defs.post import LofterPost from defs.post import LofterPost
from init import bot
@Client.on_message( @bot.on_message(
filters.incoming filters.incoming
& filters.private & filters.private
& filters.user(admin) & filters.user(admin)

View File

@ -1,12 +1,14 @@
from pyrogram import Client, filters, ContinuePropagation from pyrogram import Client, filters, ContinuePropagation
from pyrogram.types import Message from pyrogram.types import Message
from init import bot
last_msg = {} last_msg = {}
last_repeat_msg = {} last_repeat_msg = {}
repeat_count = {} repeat_count = {}
@Client.on_message(filters.incoming & filters.group) @bot.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

@ -1,12 +1,14 @@
from pyrogram import Client, filters from pyrogram import Client, filters
from pyrogram.types import Message from pyrogram.types import Message, InlineQuery
from defs.splash import update_splash from defs.glover import admin
from defs.splash import update_splash, get_inline_results
from init import bot
from scheduler import scheduler from scheduler import scheduler
@Client.on_message( @bot.on_message(
filters.incoming & filters.command(["splash_update"]) filters.incoming & filters.user(admin) & filters.command(["splash_update"])
) )
async def splash_update(_: Client, message: Message): async def splash_update(_: Client, message: Message):
""" """
@ -19,3 +21,23 @@ async def splash_update(_: Client, message: Message):
@scheduler.scheduled_job("interval", minutes=30, id="splash_update") @scheduler.scheduled_job("interval", minutes=30, id="splash_update")
async def splash_update_job() -> None: async def splash_update_job() -> None:
await update_splash() await update_splash()
@bot.on_inline_query(filters.regex(r"^m$"))
async def splash_query(_: Client, inline_query: InlineQuery):
results = await get_inline_results()
if not results:
await inline_query.answer(
results=[],
switch_pm_text="暂无启动图数据",
switch_pm_parameter="start",
cache_time=0,
)
else:
await inline_query.answer(
results=results,
switch_pm_text=f"{len(results)} 张启动图",
switch_pm_parameter="start",
cache_time=0,
)
inline_query.stop_propagation()

View File

@ -1,6 +1,7 @@
from pyrogram import Client, filters from pyrogram import Client, filters
from pyrogram.types import Message from pyrogram.types import Message, InlineQuery, InlineQueryResultArticle, InputTextMessageContent
from defs.button import gen_button, Button from defs.button import gen_button, Button
from init import bot
des = """本机器人特性: des = """本机器人特性:
@ -16,7 +17,7 @@ des = """本机器人特性:
""" """
@Client.on_message(filters.incoming & filters.private & filters.command(["start"])) @bot.on_message(filters.incoming & filters.private & filters.command(["start"]))
async def start_command(_: Client, message: Message): async def start_command(_: Client, message: Message):
""" """
回应机器人信息 回应机器人信息
@ -31,3 +32,25 @@ async def start_command(_: Client, message: Message):
] ]
), ),
) )
@bot.on_inline_query(group=1)
async def empty_inline(_, inline_query: InlineQuery):
results = [
InlineQueryResultArticle(
title="@username",
input_message_content=InputTextMessageContent("使用 @username 来查询遗产"),
description="使用 @username 来查询遗产",
),
InlineQueryResultArticle(
title="m",
input_message_content=InputTextMessageContent("使用 m 来查询米游社启动图"),
description="使用 m 来查询米游社启动图",
),
]
return await inline_query.answer(
results=results,
switch_pm_text="使用关键词开始查询",
switch_pm_parameter="start",
cache_time=0,
)