You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
3.4KB

  1. import os
  2. import logging
  3. logging.basicConfig(
  4. format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s',
  5. level=logging.DEBUG if os.environ.get('DEBUG') else logging.INFO)
  6. import settings
  7. import asyncio
  8. import json
  9. import requests
  10. from datetime import datetime
  11. from uuid import uuid4
  12. from telethon import TelegramClient, events
  13. from aiohttp import web
  14. bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH).start(bot_token=settings.API_TOKEN)
  15. TANNER = 79316791
  16. messages = {}
  17. def controller_message(message):
  18. payload = dict(misc=message)
  19. r = requests.post('https://tbot.tannercollin.com/message', data=payload, timeout=10)
  20. if r.status_code == 200:
  21. return True
  22. else:
  23. logging.exception('Unable to communicate with controller! Message: ' + message)
  24. return False
  25. @bot.on(events.NewMessage(incoming=True))
  26. async def new_message(event):
  27. text = event.raw_text
  28. sender = event.sender_id
  29. logging.info('{} {}'.format(sender, text))
  30. if sender != TANNER:
  31. return
  32. if not text.startswith('/allow_'):
  33. return
  34. mid = text.replace('/allow_', '')
  35. try:
  36. data = messages[mid]
  37. except KeyError:
  38. await event.reply('Message ID not found. Did the bot restart?')
  39. return
  40. entry = '------------------------------------------------------------\n\n{} - {}'.format(data['date'], data['name'])
  41. website = data['website']
  42. if website:
  43. prefixes = ['http://', 'https://', 'gemini://', 'gopher://']
  44. for prefix in prefixes:
  45. if website.startswith(prefix):
  46. break
  47. else: # for loop
  48. website = 'http://' + website
  49. entry += ' (<a href="{0}" target="_blank" rel="noreferrer noopener">{0}</a>)'.format(website)
  50. entry += '\n\n{}\n\n'.format(data['message'])
  51. with open('data/g/index.html', 'a') as f:
  52. f.write(entry)
  53. await event.reply('Entry added to t0.vc/g')
  54. logging.info('Added: {}'.format(data))
  55. async def submit(request):
  56. data = dict(await request.post())
  57. data['date'] = str(datetime.today().date())
  58. mid = str(uuid4()).split('-')[0]
  59. logging.info('{} {}'.format(mid, data))
  60. try:
  61. name = data['name']
  62. website = data.get('website', '')
  63. message = data['message']
  64. except KeyError:
  65. raise web.HTTPBadRequest(reason='You are missing something.')
  66. if not len(name) or not len(message):
  67. raise web.HTTPBadRequest(reason='You are missing something.')
  68. if len(name) > 50:
  69. raise web.HTTPBadRequest(reason='Name is too long.')
  70. if len(website) > 100:
  71. raise web.HTTPBadRequest(reason='Website is too long.')
  72. if len(message) > 1000:
  73. raise web.HTTPBadRequest(reason='Message is too long.')
  74. if 'sex' not in message and 'porn' not in message:
  75. report = 'Name: {}\n\nWebsite: {}\n\nMessage: {}\n\n/allow_{}'
  76. try:
  77. await bot.send_message(TANNER, message=report.format(name, website, message, mid))
  78. except:
  79. logging.error('Problem sending bot message.')
  80. controller_message('t0sig: problem sending bot message!')
  81. exit()
  82. messages[mid] = data
  83. with open('data/messages.log', 'a') as f:
  84. f.write(json.dumps(data)+'\n')
  85. return web.Response(text='Thanks! Your message is pending approval.')
  86. if __name__ == '__main__':
  87. bot.start()
  88. app = web.Application()
  89. app.router.add_post('/', submit)
  90. web.run_app(app, port=8123)