Tidy examples and update licenses

This commit is contained in:
Lonami Exo
2019-01-07 15:48:25 +01:00
parent b57e3e3e0a
commit 00c8aa847d
8 changed files with 366 additions and 85 deletions

View File

@@ -6,26 +6,17 @@ This script assumes that you have certain files on the working directory,
such as "xfiles.m4a" or "anytime.png" for some of the automated replies.
"""
import os
import re
import sys
import time
from collections import defaultdict
from datetime import datetime, timedelta
from telethon import TelegramClient, events
"""Uncomment this for debugging
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('dbg')
logging.info('info')
"""
logging.basicConfig(level=logging.WARNING)
REACTS = {'emacs': 'Needs more vim',
'chrome': 'Needs more Firefox'}
# A list of dates of reactions we've sent, so we can keep track of floods
recent_reacts = defaultdict(list)
# "When did we last react?" dictionary, 0.0 by default
recent_reacts = defaultdict(float)
def get_env(name, message, cast=str):
@@ -40,6 +31,60 @@ def get_env(name, message, cast=str):
time.sleep(1)
def can_react(chat_id):
# Get the time when we last sent a reaction (or 0)
last = recent_reacts[chat_id]
# Get the current time
now = time.time()
# If 10 minutes as seconds have passed, we can react
if now - last < 10 * 60:
# Make sure we updated the last reaction time
recent_reacts[chat_id] = now
return True
else:
return False
# Register `events.NewMessage` before defining the client.
# Once you have a client, `add_event_handler` will use this event.
@events.register(events.NewMessage)
async def handler(event):
# There are better ways to do this, but this is simple.
# If the message is not outgoing (i.e. someone else sent it)
if not event.out:
if 'emacs' in event.raw_text:
if can_react(event.chat_id):
await event.reply('> emacs\nneeds more vim')
elif 'vim' in event.raw_text:
if can_react(event.chat_id):
await event.reply('> vim\nneeds more emacs')
elif 'chrome' in event.raw_text:
if can_react(event.chat_id):
await event.reply('> chrome\nneeds more firefox')
# Reply always responds as a reply. We can respond without replying too
if 'shrug' in event.raw_text:
if can_react(event.chat_id):
await event.respond(r'¯\_(ツ)_/¯')
# We can also use client methods from here
client = event.client
# If we sent the message, we are replying to someone,
# and we said "save pic" in the message
if event.out and event.reply_to_msg_id and 'save pic' in event.raw_text:
reply_msg = await event.get_reply_message()
replied_to_user = await reply_msg.get_input_sender()
message = await event.reply('Downloading your profile photo...')
file = await client.download_profile_photo(replied_to_user)
await message.edit('I saved your photo in {}'.format(file))
client = TelegramClient(
os.environ.get('TG_SESSION', 'replier'),
get_env('TG_API_ID', 'Enter your API ID: ', int),
@@ -47,45 +92,9 @@ client = TelegramClient(
proxy=None
)
with client:
# This remembers the events.NewMessage we registered before
client.add_event_handler(handler)
@client.on(events.NewMessage)
async def my_handler(event: events.NewMessage.Event):
global recent_reacts
# Through event.raw_text we access the text of messages without format
words = re.split('\W+', event.raw_text)
# Try to match some reaction
for trigger, response in REACTS.items():
if len(recent_reacts[event.chat_id]) > 3:
# Silently ignore triggers if we've recently sent 3 reactions
break
if trigger in words:
# Remove recent replies older than 10 minutes
recent_reacts[event.chat_id] = [
a for a in recent_reacts[event.chat_id] if
datetime.now() - a < timedelta(minutes=10)
]
# Send a reaction as a reply (otherwise, event.respond())
await event.reply(response)
# Add this reaction to the list of recent actions
recent_reacts[event.chat_id].append(datetime.now())
# Automatically send relevant media when we say certain things
# When invoking requests, get_input_entity needs to be called manually
if event.out:
chat = await event.get_input_chat()
if event.raw_text.lower() == 'x files theme':
await client.send_file(chat, 'xfiles.m4a',
reply_to=event.message.id, voice_note=True)
if event.raw_text.lower() == 'anytime':
await client.send_file(chat, 'anytime.png',
reply_to=event.message.id)
if '.shrug' in event.text:
await event.edit(event.text.replace('.shrug', r'¯\_(ツ)_/¯'))
with client.start():
print('(Press Ctrl+C to stop this)')
client.run_until_disconnected()