PaiGram/plugins/base.py

67 lines
3.2 KiB
Python
Raw Normal View History

2022-04-14 07:18:45 +00:00
import datetime
from telegram import Update
from telegram.error import BadRequest
2022-05-18 14:09:07 +00:00
from telegram.ext import CallbackContext, ConversationHandler, filters
from telegram.ext._utils.types import HandlerCallback, CCT, RT
2022-04-14 07:18:45 +00:00
from logger import Log
2022-05-18 14:09:07 +00:00
from model.helpers import get_admin_list
2022-04-14 07:18:45 +00:00
from service import BaseService
class BasePlugins:
def __init__(self, service: BaseService):
self.service = service
@staticmethod
async def cancel(update: Update, _: CallbackContext) -> int:
await update.message.reply_text("退出命令")
return ConversationHandler.END
@staticmethod
async def _clean(context: CallbackContext, chat_id: int, message_id: int) -> bool:
try:
2022-05-16 09:46:27 +00:00
await context.bot.delete_message(chat_id=chat_id, message_id=message_id)
return True
except BadRequest as error:
if "not found" in str(error):
2022-05-18 12:37:44 +00:00
Log.warning(f"定时删除消息 chat_id[{chat_id}] message_id[{message_id}]失败 消息不存在")
elif "Message can't be deleted" in str(error):
Log.warning(f"定时删除消息 chat_id[{chat_id}] message_id[{message_id}]失败 消息无法删除 可能是没有授权")
else:
2022-05-18 12:37:44 +00:00
Log.warning(f"定时删除消息 chat_id[{chat_id}] message_id[{message_id}]失败 \n", error)
return False
2022-04-14 07:18:45 +00:00
def _add_delete_message_job(self, context: CallbackContext, chat_id: int, message_id: int,
2022-04-20 08:18:55 +00:00
delete_seconds: int = 60):
2022-04-14 07:18:45 +00:00
context.job_queue.scheduler.add_job(self._clean, "date",
id=f"{chat_id}|{message_id}|auto_clean_message",
name=f"{chat_id}|{message_id}|auto_clean_message",
args=[context, chat_id, message_id],
run_date=context.job_queue._tz_now() + datetime.timedelta(
seconds=delete_seconds), replace_existing=True)
2022-05-18 14:09:07 +00:00
class NewChatMembersHandler:
def __init__(self, service: BaseService, auth_callback: HandlerCallback[Update, CCT, RT]):
self.service = service
self.auth_callback = auth_callback
async def new_member(self, update: Update, context: CallbackContext) -> None:
message = update.message
chat = message.chat
from_user = message.from_user
if filters.ChatType.GROUPS.filter(message):
for user in message.new_chat_members:
if user.id == context.bot.id:
if from_user is not None:
admin_list = await self.service.admin.get_admin_list()
if from_user.id in admin_list:
await context.bot.send_message(message.chat_id,
'感谢邀请小派蒙到本群!请使用 /help 查看咱已经学会的功能。')
else:
await context.bot.send_message(message.chat_id, "派蒙不想进去!不是旅行者的邀请!")
await context.bot.leave_chat(chat.id)
await self.auth_callback(update, context)