Add logs and file log, set some admin commands and add chat actions
This commit is contained in:
parent
4887fe952b
commit
283da53180
1 changed files with 72 additions and 17 deletions
89
bot.py
89
bot.py
|
@ -8,9 +8,27 @@ from requests import get
|
||||||
from requests.exceptions import ConnectionError, InvalidSchema, MissingSchema
|
from requests.exceptions import ConnectionError, InvalidSchema, MissingSchema
|
||||||
from threading import RLock
|
from threading import RLock
|
||||||
from asyncio import sleep
|
from asyncio import sleep
|
||||||
|
from os import mkdir
|
||||||
|
from os.path import isdir, isfile
|
||||||
|
|
||||||
|
|
||||||
|
if not isdir("logs"):
|
||||||
|
mkdir("logs")
|
||||||
|
|
||||||
|
logger = logging.getLogger("TelegramEDT")
|
||||||
|
log_date = datetime.datetime.now(datetime.timezone.utc).astimezone(tz=None).date()
|
||||||
|
logging.basicConfig(
|
||||||
|
filename=f"logs/{log_date}.log",
|
||||||
|
format="{%(levelname)s}[%(asctime)s]: %(name)s | %(message)s",
|
||||||
|
level=logging.INFO,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not isfile("token.ini"):
|
||||||
|
logger.critical("No token specified, impossible to start the bot !")
|
||||||
|
exit(1)
|
||||||
API_TOKEN = open("token.ini").read()
|
API_TOKEN = open("token.ini").read()
|
||||||
logging.basicConfig(level=logging.INFO)
|
ADMIN_ID = 148441652
|
||||||
|
|
||||||
bot = Bot(token=API_TOKEN)
|
bot = Bot(token=API_TOKEN)
|
||||||
dp = Dispatcher(bot)
|
dp = Dispatcher(bot)
|
||||||
dbL = RLock()
|
dbL = RLock()
|
||||||
|
@ -82,12 +100,31 @@ async def notif():
|
||||||
await sleep(60)
|
await sleep(60)
|
||||||
|
|
||||||
|
|
||||||
|
@dp.inline_handler()
|
||||||
|
async def inline_echo(inline_query: InlineQuery):
|
||||||
|
text = inline_query.query
|
||||||
|
if text not in ["day", "week", "next", ""]:
|
||||||
|
text = "invalid"
|
||||||
|
res = edt(text, inline_query.from_user.id)
|
||||||
|
input_content = InputTextMessageContent(res, parse_mode=ParseMode.MARKDOWN)
|
||||||
|
result_id: str = hashlib.md5(res.encode()).hexdigest()
|
||||||
|
item = InlineQueryResultArticle(
|
||||||
|
id=result_id,
|
||||||
|
title=f"Your {text} course",
|
||||||
|
input_message_content=input_content,
|
||||||
|
)
|
||||||
|
await bot.answer_inline_query(inline_query.id, results=[item], cache_time=1)
|
||||||
|
|
||||||
|
|
||||||
@dp.message_handler(commands=["start", "help"])
|
@dp.message_handler(commands=["start", "help"])
|
||||||
async def send_welcome(message: types.Message):
|
async def send_welcome(message: types.Message):
|
||||||
|
await message.chat.do(types.ChatActions.TYPING)
|
||||||
|
logger.info(f"{message.from_user.username} do start/help command: {message.text}")
|
||||||
with dbL:
|
with dbL:
|
||||||
with shelve.open("edt", writeback=True) as db:
|
with shelve.open("edt", writeback=True) as db:
|
||||||
if str(message.from_user.id) not in db:
|
if str(message.from_user.id) not in db:
|
||||||
db[str(message.from_user.id)] = dict()
|
db[str(message.from_user.id)] = dict()
|
||||||
|
logger.info(f"db creation for {message.from_user.username}")
|
||||||
|
|
||||||
msg = markdown.text(
|
msg = markdown.text(
|
||||||
markdown.text("💠 Welcome to the TelegramEDT, a calendar bot for the Lyon 1 University ! 💠\n"),
|
markdown.text("💠 Welcome to the TelegramEDT, a calendar bot for the Lyon 1 University ! 💠\n"),
|
||||||
|
@ -124,6 +161,8 @@ async def send_welcome(message: types.Message):
|
||||||
@dp.message_handler(commands=["edt"])
|
@dp.message_handler(commands=["edt"])
|
||||||
@dp.message_handler(lambda msg: msg.text.lower() in ["day", "week", "next"])
|
@dp.message_handler(lambda msg: msg.text.lower() in ["day", "week", "next"])
|
||||||
async def edt_cmd(message: types.Message):
|
async def edt_cmd(message: types.Message):
|
||||||
|
await message.chat.do(types.ChatActions.TYPING)
|
||||||
|
logger.info(f"{message.from_user.username} do edt command: {message.text}")
|
||||||
text = message.text
|
text = message.text
|
||||||
if message.text[:4] == "/edt":
|
if message.text[:4] == "/edt":
|
||||||
text = message.text[5:]
|
text = message.text[5:]
|
||||||
|
@ -135,24 +174,10 @@ async def edt_cmd(message: types.Message):
|
||||||
await message.reply(resp, parse_mode=ParseMode.MARKDOWN, reply_markup=key)
|
await message.reply(resp, parse_mode=ParseMode.MARKDOWN, reply_markup=key)
|
||||||
|
|
||||||
|
|
||||||
@dp.inline_handler()
|
|
||||||
async def inline_echo(inline_query: InlineQuery):
|
|
||||||
text = inline_query.query
|
|
||||||
if text not in ["day", "week", "next", ""]:
|
|
||||||
text = "invalid"
|
|
||||||
res = edt(text, inline_query.from_user.id)
|
|
||||||
input_content = InputTextMessageContent(res)
|
|
||||||
result_id: str = hashlib.md5(res.encode()).hexdigest()
|
|
||||||
item = InlineQueryResultArticle(
|
|
||||||
id=result_id,
|
|
||||||
title=f"Your {text} course",
|
|
||||||
input_message_content=input_content
|
|
||||||
)
|
|
||||||
await bot.answer_inline_query(inline_query.id, results=[item], cache_time=1)
|
|
||||||
|
|
||||||
|
|
||||||
@dp.message_handler(commands=["setedt"])
|
@dp.message_handler(commands=["setedt"])
|
||||||
async def edt_set(message: types.Message):
|
async def edt_set(message: types.Message):
|
||||||
|
await message.chat.do(types.ChatActions.TYPING)
|
||||||
|
logger.info(f"{message.from_user.username} do setedt command: {message.text}")
|
||||||
url_http = message.text.find("http")
|
url_http = message.text.find("http")
|
||||||
url_end = message.text.find(" ", url_http)
|
url_end = message.text.find(" ", url_http)
|
||||||
if url_end == -1:
|
if url_end == -1:
|
||||||
|
@ -179,6 +204,8 @@ async def edt_set(message: types.Message):
|
||||||
|
|
||||||
@dp.message_handler(commands=["getedt"])
|
@dp.message_handler(commands=["getedt"])
|
||||||
async def edt_geturl(message: types.Message):
|
async def edt_geturl(message: types.Message):
|
||||||
|
await message.chat.do(types.ChatActions.TYPING)
|
||||||
|
logger.info(f"{message.from_user.username} do getedt command: {message.text}")
|
||||||
with dbL:
|
with dbL:
|
||||||
with shelve.open("edt", writeback=True) as db:
|
with shelve.open("edt", writeback=True) as db:
|
||||||
if (str(message.from_user.id) in db) and ("url" in db[str(message.from_user.id)]):
|
if (str(message.from_user.id) in db) and ("url" in db[str(message.from_user.id)]):
|
||||||
|
@ -189,6 +216,8 @@ async def edt_geturl(message: types.Message):
|
||||||
|
|
||||||
@dp.message_handler(commands=["notif"])
|
@dp.message_handler(commands=["notif"])
|
||||||
async def notif_cmd(message: types.Message):
|
async def notif_cmd(message: types.Message):
|
||||||
|
await message.chat.do(types.ChatActions.TYPING)
|
||||||
|
logger.info(f"{message.from_user.username} do notif command: {message.text}")
|
||||||
with dbL:
|
with dbL:
|
||||||
with shelve.open("edt", writeback=True) as db:
|
with shelve.open("edt", writeback=True) as db:
|
||||||
if "notif" not in db[str(message.from_user.id)]:
|
if "notif" not in db[str(message.from_user.id)]:
|
||||||
|
@ -251,6 +280,32 @@ async def notif_cmd(message: types.Message):
|
||||||
await message.reply(msg, parse_mode=ParseMode.MARKDOWN)
|
await message.reply(msg, parse_mode=ParseMode.MARKDOWN)
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=["getid"])
|
||||||
|
async def get_id(message: types.Message):
|
||||||
|
await message.chat.do(types.ChatActions.TYPING)
|
||||||
|
logger.info(f"{message.from_user.username} do getid command: {message.text}")
|
||||||
|
await message.reply(message.from_user.id)
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=["getlogs"])
|
||||||
|
async def get_logs(message: types.Message):
|
||||||
|
logger.info(f"{message.from_user.username} do getlog command: {message.text}")
|
||||||
|
if message.from_user.id == ADMIN_ID:
|
||||||
|
await message.chat.do(types.ChatActions.UPLOAD_DOCUMENT)
|
||||||
|
await message.reply_document(types.InputFile(f"logs/{log_date}.log"), caption=f"The {log_date} logs")
|
||||||
|
|
||||||
|
|
||||||
|
@dp.errors_handler()
|
||||||
|
async def errors(*args, **partial_data):
|
||||||
|
msg = markdown.text(
|
||||||
|
markdown.bold("⚠️ An error occurred:"),
|
||||||
|
markdown.code(args),
|
||||||
|
markdown.code(partial_data),
|
||||||
|
sep="\n"
|
||||||
|
)
|
||||||
|
await bot.send_message(ADMIN_ID, msg, parse_mode=ParseMode.MARKDOWN)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
loop.create_task(notif())
|
loop.create_task(notif())
|
||||||
|
|
Reference in a new issue