Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Troutslap #2

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 15 additions & 2 deletions README.md
Expand Up @@ -8,8 +8,21 @@ Requirements

- Python >= 3.3
- hangups (https://github.com/tdryer/hangups)
- appdirs (https://github.com/ActiveState/appdirs)
- asyncio (https://pypi.python.org/pypi/asyncio) for Python < 3.4

Setup
-----

Install package `python-virtualenv`

Make a virtual environment `virtualenv .venv`

Install package `python-pip`

Install hangupsbot dependency `pip3 install hangups`

Install hangupsbot `python3 setup.py install`

Run hangupsbot `hangupsbot`

Usage
-----
Expand Down
26 changes: 26 additions & 0 deletions etc/dilbot.json
@@ -0,0 +1,26 @@
{
"admins": ["USER1_ID", "USER2_ID"],
"autoreplies": [
[["^sup$"], "sup"],
[["^.*[Dd]*ilbert\\?.*$"], "here you go faggots http://dilbert.com/"]
],
"autoreplies_enabled": true,
"commands_admin": ["rename", "leave", "easteregg", "user", "users", "hangouts", "reload", "quit", "config"],
"commands_enabled": true,
"forwarding_enabled": true,
"conversations": {
"CONV1_ID": {
"forward_to": [
"CONV2_ID"
]
},
"CONV2_ID": {
"autoreplies_enabled": false,
"commands_enabled": false,
"forwarding_enabled": false,
"forward_to": [
"CONV1_ID"
]
}
}
}
47 changes: 39 additions & 8 deletions hangupsbot/commands.py
@@ -1,8 +1,9 @@
import sys, json, random, asyncio

import time
import hangups
from hangups.ui.utils import get_conv_name

from datetime import date as datetime
from hangups.ui.utils import get_conv_name
from hangupsbot.utils import text_to_segments


Expand Down Expand Up @@ -52,14 +53,14 @@ def register_unknown(self, func):
def unknown_command(bot, event, *args):
"""Unknown command handler"""
bot.send_message(event.conv,
'{}: Ja ne znaju, ne ponimaju!'.format(event.user.full_name))
'English mother fucker. Do you speak it?')


@command.register
def help(bot, event, cmd=None, *args):
"""Help me, Obi-Wan Kenobi. You're my only hope."""
if not cmd:
segments = [hangups.ChatMessageSegment('Podporované příkazy:', is_bold=True),
segments = [hangups.ChatMessageSegment('My available commands:', is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment(', '.join(sorted(command.commands.keys())))]
else:
Expand Down Expand Up @@ -90,7 +91,7 @@ def echo(bot, event, *args):
@command.register
def users(bot, event, *args):
"""Výpis všech uživatelů v aktuálním Hangoutu (včetně G+ účtů a emailů)"""
segments = [hangups.ChatMessageSegment('Seznam uživatelů (celkem {}):'.format(len(event.conv.users)),
segments = [hangups.ChatMessageSegment('Users in chat ({}):'.format(len(event.conv.users)),
is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)]
for u in sorted(event.conv.users, key=lambda x: x.full_name.split()[-1]):
Expand All @@ -110,7 +111,7 @@ def users(bot, event, *args):
def user(bot, event, username, *args):
"""Vyhledá uživatele podle jména"""
username_lower = username.strip().lower()
segments = [hangups.ChatMessageSegment('Výsledky hledání uživatelů jménem "{}":'.format(username),
segments = [hangups.ChatMessageSegment('Here are the users I could find "{}":'.format(username),
is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)]
for u in sorted(bot._user_list._user_dict.values(), key=lambda x: x.full_name.split()[-1]):
Expand All @@ -134,7 +135,7 @@ def user(bot, event, username, *args):
def hangouts(bot, event, *args):
"""Výpis všech aktivních Hangoutů, v kterých řádí bot
Vysvětlivky: c ... commands, f ... forwarding, a ... autoreplies"""
segments = [hangups.ChatMessageSegment('Seznam aktivních Hangoutů:', is_bold=True),
segments = [hangups.ChatMessageSegment('Hangous I am in:', is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)]
for c in bot.list_conversations():
s = '{} [c: {:d}, f: {:d}, a: {:d}]'.format(get_conv_name(c, truncate=True),
Expand Down Expand Up @@ -167,7 +168,7 @@ def leave(bot, event, conversation=None, *args):

for c in convs:
yield from c.send_message([
hangups.ChatMessageSegment('I\'ll be back!')
hangups.ChatMessageSegment('I\'ll be back.')
])
yield from bot._conv_list.delete_conversation(c.id_)

Expand Down Expand Up @@ -238,3 +239,33 @@ def config(bot, event, cmd=None, *args):
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)]
segments.extend(text_to_segments(json.dumps(value, indent=2, sort_keys=True)))
bot.send_message_segments(event.conv, segments)


def _random_date(start, end, format):
stime = time.mktime(time.strptime(start, format))
etime = time.mktime(time.strptime(end, format))
ptime = stime + random.random() * (etime - stime)
return time.strftime(format, time.localtime(ptime))


@command.register
def dilbert(bot, event, *args):
"""first dilbert 1989-04-16"""
dilbert_modifier = ''
for arg in list(args):
if arg == 'random':
dilbert_date_format = '%Y-%m-%d'
today = datetime.today().strftime(dilbert_date_format)
dilbert_modifier = _random_date(
'1989-04-16',
today,
dilbert_date_format)

dilbert_link = 'http://dilbert.com/{}'.format(dilbert_modifier)
message = "Here's your fucking dilbert, {}".format(dilbert_link)
bot.parse_and_send_segments(event.conv, message)

@command.register
define slap(bot, event, name):
message = "/me slaps {} around a bit with a large trout".format(name)
bot.parse_and_send_segments(event.conv, message)
18 changes: 13 additions & 5 deletions hangupsbot/handlers.py
@@ -1,7 +1,7 @@
import logging, shlex, unicodedata, asyncio

import hangups

import re
from hangupsbot.commands import command


Expand All @@ -12,6 +12,12 @@ def __init__(self, bot, bot_command='/bot'):
self.bot = bot
self.bot_command = bot_command

@staticmethod
def regex_parse_text(regex, text):
"""Return True if regex matches"""
result = re.match(regex, text)
return result

@staticmethod
def word_in_text(word, text):
"""Return True if word is in text"""
Expand Down Expand Up @@ -55,7 +61,7 @@ def handle_command(self, event):
# Test if command length is sufficient
if len(line_args) < 2:
self.bot.send_message(event.conv,
'{}: Co si bude pán ráčit?'.format(event.user.full_name))
'{}: Pardon?'.format(event.user.full_name))
return

# Test if user has permissions for running command
Expand All @@ -64,7 +70,7 @@ def handle_command(self, event):
admins_list = self.bot.get_config_suboption(event.conv_id, 'admins')
if event.user_id.chat_id not in admins_list:
self.bot.send_message(event.conv,
'{}: I\'m sorry, Dave. I\'m afraid I can\'t do that.'.format(event.user.full_name))
'I\'m sorry, {}. I\'m afraid I can\'t do that.'.format(event.user.full_name))
return

# Run command
Expand Down Expand Up @@ -110,6 +116,8 @@ def handle_autoreply(self, event):
if autoreplies_list:
for kwds, sentence in autoreplies_list:
for kw in kwds:
if self.word_in_text(kw, event.text) or kw == "*":
self.bot.send_message(event.conv, sentence)
# if self.word_in_text(kw, event.text) or kw == "*":
if self.regex_parse_text(kw, event.text):
# self.bot.send_message(event.conv, sentence)
self.bot.parse_and_send_segments(event.conv, sentence)
break
11 changes: 11 additions & 0 deletions hangupsbot/hangupsbot.py
Expand Up @@ -178,6 +178,17 @@ def send_message_segments(self, conversation, segments):
conversation.send_message(segments)
).add_done_callback(self._on_message_sent)

def parse_and_send_segments(self, conversation, text):
"""Will parse out links to be clickable"""
# Ignore if the user hasn't typed a message.
if len(text) == 0:
return

segments = hangups.ChatMessageSegment.from_str(text)
asyncio.async(
conversation.send_message(segments)
).add_done_callback(self._on_message_sent)

def list_conversations(self):
"""List all active conversations"""
convs = sorted(self._conv_list.get_all(),
Expand Down