Skip to content

Commit ea6cd4f

Browse files
Merge pull request #51 from OperationCode/staging
Staging
2 parents 57d97f9 + 063d3cd commit ea6cd4f

5 files changed

Lines changed: 65 additions & 53 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
*.env
33
.pytest_cache
44
!/docker/example.env
5+
*/__pycache__

pybot/endpoints/slack/commands.py

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
from pybot.endpoints.slack.utils.action_messages import not_claimed_attachment
1010
from pybot.endpoints.slack.utils.command_utils import get_slash_here_messages, get_slash_repeat_messages, response_type
1111
from pybot.endpoints.slack.utils.slash_lunch import LunchCommand
12-
from pybot.endpoints.slack.utils.slash_tech import TechTerms
1312

1413
logger = logging.getLogger(__name__)
1514

@@ -24,7 +23,6 @@ def create_endpoints(plugin: SlackPlugin):
2423
plugin.on_command('/here', slash_here, wait=False)
2524
plugin.on_command('/lunch', slash_lunch, wait=False)
2625
plugin.on_command('/repeat', slash_repeat, wait=False)
27-
plugin.on_command('/tech', slash_tech, wait=False)
2826
plugin.on_command('/report', slash_report, wait=False)
2927

3028

@@ -107,22 +105,3 @@ async def slash_repeat(command: Command, app: SirBot):
107105

108106
method_type, message = get_slash_repeat_messages(slack_id, channel_id, command['text'])
109107
await slack.query(method_type, message)
110-
111-
112-
async def slash_tech(command: Command, app: SirBot):
113-
logger.info(f'tech command data incoming {command}')
114-
channel_id = command['channel_id']
115-
slack_id = command['user_id']
116-
slack = app["plugins"]["slack"].api
117-
118-
tech_terms: dict = TechTerms(command['channel_id'], command['user_id'],
119-
command.get('text'), command['user_name'], app).grab_values()
120-
method_type = response_type(tech_terms['type'])
121-
text = tech_terms['message']
122-
message = {
123-
'text': text,
124-
'channel': channel_id,
125-
'user': slack_id
126-
}
127-
128-
await slack.query(method_type, message)

pybot/endpoints/slack/event_messages/__init__.py

Whitespace-only changes.

pybot/endpoints/slack/utils/slash_tech.py renamed to pybot/endpoints/slack/event_messages/tech.py

Lines changed: 29 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,15 @@ async def _update_terms(self) -> Dict[str, list]:
2525
two_col_org_row: Pattern[str] = self._compile_regex_from_parts()
2626

2727
content = await self._grab_data_from_github()
28-
2928
lines: List[str] = content.splitlines()
3029

31-
return {x['term'].lower(): 'f{x["term"]} is x["definition"]}' for x in
30+
return {x['term'].lower(): f'{x["term"]} is {x["definition"]}' for x in
3231
self._filter_matches(lines, two_col_org_row)}
3332

3433
async def _grab_data_from_github(self) -> str:
3534
async with self.app.http_session.get(self.TERM_URL) as r:
3635
r.raise_for_status()
37-
data = await r.json()
38-
return data.decode('utf-8')
36+
return await r.text(encoding='utf-8')
3937

4038
def _compile_regex_from_parts(self) -> Pattern[str]:
4139
n_spaces_pipe_n_spaces = '\\s*\\|\\s*'
@@ -55,64 +53,64 @@ def _filter_matches(self, lines: List[str], two_col_org_row: Pattern[str]) -> Ge
5553
class TechTerms:
5654
# shared across all instances
5755
TERMS = {}
58-
ADD_GITHUB_CHANCE = .25
56+
ADD_GITHUB_CHANCE = 1
5957

60-
def __init__(self, channel: str, user: str, input_text: str, user_name: str, app):
58+
def __init__(self, channel: str, user: str, input_text: str, app):
6159

6260
self.channel_id = channel
6361
self.user_id = user
64-
self.input_text = input_text
65-
self.user_name = user_name
62+
self.input_text = self.remove_tech(input_text)
6663
self.app = app
64+
self.response_params = None
6765

68-
self.response_params = self._parse_input()
66+
def remove_tech(self, initial_input):
67+
return initial_input.split('!tech', 1)[1]
6968

70-
def grab_values(self) -> dict:
69+
async def grab_values(self) -> dict:
7170
if not self.input_text:
72-
return {'type': 'ephemeral', 'message': self._help_text()}
71+
return {'message': {'text' : self._help_text(), 'channel': self.channel_id,}}
7372

7473
else:
74+
if not self.response_params:
75+
await self._parse_input()
7576

76-
split_items: List[str] = self.input_text.split()
77-
if split_items[0] == 'loud':
78-
return {'type': 'loud', 'message': self._grab_term(split_items)}
79-
80-
if split_items[0] == 'loud':
81-
return {'type': 'loud', 'message': self._grab_term(split_items)}
77+
if self.input_text:
78+
return {'message': self._grab_term(term=self.input_text)}
8279

83-
return {'type': 'ephemeral', 'message': self._grab_term(), }
80+
return {'message': self._grab_term(), }
8481

8582
async def _parse_input(self) -> None:
86-
self.TERMS = await TechTermsGrabber(self.app).get_terms()
83+
grabber = TechTermsGrabber(self.app)
84+
self.TERMS = await grabber.get_terms()
8785

8886
def _help_text(self):
8987
return ('Use this to find descriptions of common and useful tech terms. Examples:\n' +
90-
'"/resources Javascript", for self study\n' +
91-
'"/resources loud Javascript", to announce to channel' +
88+
'"!tech Java" or "!tech prolog"' +
9289
self._source_text())
9390

9491
def _source_text(self):
95-
return '\nFor the source data please see <github|https://github.com/togakangaroo/tech-terms>'
92+
return '\nTech Terms source: <https://github.com/togakangaroo/tech-terms|github>'
9693

97-
def _convert_key_to_dict(self, key: str) -> dict:
98-
return {'term': key, 'definition': self.TERMS[key]}
94+
def _convert_key_to_dict(self, key: str, random_val: bool = False) -> dict:
95+
return {'term': key, 'random': random_val, 'definition': f'{self.TERMS[key]}'}
9996

10097
def _grab_term(self, term=None):
101-
if isinstance(term, list) and len(term) > 1 and self.TERMS.get(term[1].lower()):
102-
term_key: str = self.TERMS.get(term[1])
98+
if term and self.TERMS.get(term.lower().strip()):
99+
term_key: str = term.lower().strip()
103100
return self._build_response_text(self._convert_key_to_dict(term_key))
104101

105102
return self._build_response_text(self._random_term())
106103

107104
def _build_response_text(self, term: dict) -> dict:
108-
return {'user': self.user_id, 'channel': self.channel_id,
105+
return {'channel': self.channel_id,
109106
'text': self._serialize_term(term)}
110107

111108
def _random_term(self) -> dict:
112-
item = choice(self.TERMS.keys())
113-
return self._convert_key_to_dict(item)
109+
item = choice(list(self.TERMS.keys()))
110+
return self._convert_key_to_dict(item, random_val=True)
114111

115112
def _serialize_term(self, term: Dict[str, str]) -> str:
116-
addnl = self._source_text() if random.random() < self.ADD_GITHUB_CHANCE else ''
113+
random_text = "Selected random term:\n"
114+
addnl = self._source_text() if random() < self.ADD_GITHUB_CHANCE else ''
117115

118-
return f'{term["definition"]}{addnl}'
116+
return f'{random_text if term["random"] else ""} {term["definition"]}{addnl}'

pybot/endpoints/slack/messages.py

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,57 @@
22

33
from sirbot import SirBot
44
from slack.events import Message
5+
from slack import methods
6+
7+
from pybot.endpoints.slack.event_messages.tech import TechTerms
58

69
logger = logging.getLogger(__name__)
710

811

912
def create_endpoints(plugin):
1013
plugin.on_message(".*", message_changed, subtype="message_changed")
1114
plugin.on_message(".*", message_deleted, subtype="message_deleted")
15+
plugin.on_message(".*\!tech", tech_tips)
16+
plugin.on_message(".*\<\!here\>", here_bad)
17+
plugin.on_message(".*\<\!channel\>", here_bad)
18+
plugin.on_message(".*\@here", here_bad)
19+
plugin.on_message(".*\@channel", here_bad)
20+
plugin.on_message(".*@here", here_bad)
21+
plugin.on_message(".*@channel", here_bad)
22+
plugin.on_message(".*codervets", not_named)
1223

1324

1425
def not_bot_message(event: Message):
1526
return 'message' not in event or 'subtype' not in event['message'] or event['message']['subtype'] != 'bot_message'
1627

17-
1828
def not_bot_delete(event: Message):
1929
return 'previous_message' not in event or 'bot_id' not in event['previous_message']
2030

2131

32+
async def not_named(event: Message, app: SirBot):
33+
response = {'channel': event['channel'], 'text': f'<@{event["user"]}> - How dare you utter the Dark Lord\'s name'}
34+
await app.plugins["slack"].api.query(methods.CHAT_POST_MESSAGE, data=response)
35+
36+
37+
async def here_bad(event: Message, app: SirBot):
38+
response = {'channel': event['channel'],
39+
'text': f'<@{event["user"]}> - you are a very bad person for using that command'}
40+
await app.plugins["slack"].api.query(methods.CHAT_POST_MESSAGE, data=response)
41+
42+
43+
async def tech_tips(event: Message, app: SirBot):
44+
if not_bot_message(event):
45+
logger.info(
46+
f'tech logging: {event}')
47+
try:
48+
tech_terms: dict = await TechTerms(event['channel'], event['user'],
49+
event.get('text'), app).grab_values()
50+
51+
await app.plugins["slack"].api.query(methods.CHAT_POST_MESSAGE, tech_terms['message'])
52+
except Exception as E:
53+
logger.exception(E)
54+
55+
2256
async def message_changed(event: Message, app: SirBot):
2357
"""
2458
Logs all message edits not made by a bot.

0 commit comments

Comments
 (0)