t0sig/t0sig.py

134 lines
4.0 KiB
Python
Raw Permalink Normal View History

2022-01-07 00:19:01 +00:00
import os
import logging
logging.basicConfig(
format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s',
level=logging.DEBUG if os.environ.get('DEBUG') else logging.INFO)
import settings
import asyncio
2021-08-20 21:41:04 +00:00
import json
import requests
2021-08-20 21:41:04 +00:00
from datetime import datetime
from uuid import uuid4
from telethon import TelegramClient, events
from aiohttp import web
bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH).start(bot_token=settings.API_TOKEN)
2021-08-20 21:41:04 +00:00
TANNER = 79316791
messages = {}
def controller_message(message):
payload = dict(misc=message)
r = requests.post('https://tbot.tannercollin.com/message', data=payload, timeout=10)
if r.status_code == 200:
return True
else:
logging.exception('Unable to communicate with controller! Message: ' + message)
return False
@bot.on(events.NewMessage(incoming=True))
async def new_message(event):
text = event.raw_text
2021-08-20 21:41:04 +00:00
sender = event.sender_id
2022-01-07 00:19:01 +00:00
logging.info('{} {}'.format(sender, text))
2021-08-20 21:41:04 +00:00
if sender != TANNER:
return
if not text.startswith('/allow_'):
return
mid = text.replace('/allow_', '')
try:
data = messages[mid]
except KeyError:
await event.reply('Message ID not found. Did the bot restart?')
return
entry = '\n\n{} - {}'.format(data['date'], data['name'])
2021-08-20 21:41:04 +00:00
website = data['website']
if website:
2022-01-07 00:19:01 +00:00
prefixes = ['http://', 'https://', 'gemini://', 'gopher://']
for prefix in prefixes:
2023-04-29 19:38:05 +00:00
if website.lower().startswith(prefix):
2022-01-07 00:19:01 +00:00
break
else: # for loop
2021-08-20 21:41:04 +00:00
website = 'http://' + website
2022-01-07 00:19:01 +00:00
2021-08-20 21:41:04 +00:00
entry += ' (<a href="{0}" target="_blank" rel="noreferrer noopener">{0}</a>)'.format(website)
entry += '\n\n{}\n\n------------------------------------------------------------'.format(data['message'])
2021-08-20 21:41:04 +00:00
with open('data/g/index.html', 'r') as f:
page = f.read()
with open('data/g/index.html', 'w') as f:
header, entries = page.split('===========', maxsplit=1)
f.write(header)
f.write('===========')
2021-08-20 21:41:04 +00:00
f.write(entry)
f.write(entries)
2021-08-20 21:41:04 +00:00
await event.reply('Entry added to t0.vc/g')
2022-01-07 00:19:01 +00:00
logging.info('Added: {}'.format(data))
2021-08-20 21:41:04 +00:00
2024-01-04 06:15:12 +00:00
async def message_tanner(name, website, message, captcha, mid):
if 'tanner' not in captcha.lower():
2022-07-27 05:09:40 +00:00
return
2022-08-11 20:40:15 +00:00
if name.replace(' ', '') in ['website', 'webpage', 'homepage']:
return
2022-07-27 05:09:40 +00:00
report = 'Name: {}\n\nWebsite: {}\n\nMessage: {}\n\n/allow_{}'
try:
await bot.send_message(TANNER, message=report.format(name, website, message, mid))
except:
logging.error('Problem sending bot message.')
controller_message('t0sig: problem sending bot message!')
exit()
async def submit(request):
2021-08-20 21:41:04 +00:00
data = dict(await request.post())
data['date'] = str(datetime.today().date())
mid = str(uuid4()).split('-')[0]
2022-01-07 00:19:01 +00:00
logging.info('{} {}'.format(mid, data))
2021-08-20 21:41:04 +00:00
try:
2024-01-04 06:15:12 +00:00
fake_username = data.get('fake_username', '') # not used yet
2021-08-20 21:41:04 +00:00
name = data['name']
website = data.get('website', '')
message = data['message']
2024-01-04 06:15:12 +00:00
captcha = data.get('captcha', '')
2021-08-20 21:41:04 +00:00
except KeyError:
raise web.HTTPBadRequest(reason='You are missing something.')
2021-08-20 22:14:57 +00:00
if not len(name) or not len(message):
raise web.HTTPBadRequest(reason='You are missing something.')
2021-08-20 21:41:04 +00:00
if len(name) > 50:
raise web.HTTPBadRequest(reason='Name is too long.')
if len(website) > 100:
raise web.HTTPBadRequest(reason='Website is too long.')
if len(message) > 1000:
raise web.HTTPBadRequest(reason='Message is too long.')
2024-01-04 06:15:12 +00:00
await message_tanner(name, website, message, captcha, mid)
2022-07-27 05:09:40 +00:00
messages[mid] = data
2021-08-20 21:41:04 +00:00
with open('data/messages.log', 'a') as f:
f.write(json.dumps(data)+'\n')
return web.Response(text='Thanks! Your message is pending approval.')
if __name__ == '__main__':
bot.start()
app = web.Application()
app.router.add_post('/', submit)
web.run_app(app, port=8123)