Skip to content

Commit d925152

Browse files
author
lagaffe
committed
bugfixes on datetimes due to python version changes (?), debug gif plugin not handling when no gif is returned. Add sudo plugin because the funny
1 parent e3d8807 commit d925152

File tree

13 files changed

+87
-17
lines changed

13 files changed

+87
-17
lines changed

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ docker build -t lechebot .
1010
# pour usage rapide:
1111
# --rm le docker est supr au moment de le stop
1212
docker run --rm lechebot
13+
docker run -it --rm lechebot bash # run bash to manually start lechbot and choose comand line options
1314
```
1415

1516
## Installation en local
@@ -26,6 +27,16 @@ $ pip install -r requirements.txt
2627
Create a file called local_config.py (in the same directory as config.py), and edit config values as needed.
2728
In order to test the bot locally, you might be interested in runnning an instance of [UrLab's Incubator](https://github.com/UrLab/incubator).
2829

30+
to use the sudo plugin you need to add a sudoers.json files in the data/
31+
32+
sudoers.json:
33+
```json
34+
{
35+
"users": []
36+
}
37+
```
38+
with the user names of the sudoers in the users array (you can allways add some later using the bot command or modifying the file)
39+
2940
### Test in command line only
3041

3142
`$ python lechbot.py [ --debug ]`

chanconfig.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@
1414
Trump,
1515
Twitter,
1616
UrlShow,
17+
Sudo
1718
)
1819

1920
CHANS = {
2021
"#urlab": [
22+
Sudo(),
2123
Ascii(),
2224
Topic(),
2325
Space(),
@@ -34,6 +36,7 @@
3436
Trump(),
3537
],
3638
"#titoufaitdestests": [
39+
Sudo(),
3740
Ascii(),
3841
Topic(),
3942
Space(),

config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
BRIDGE_BOTS = ["LeBID"]
1313

1414
# Url to Incubator
15-
INCUBATOR = "http://localhost:8000/"
15+
INCUBATOR = "https://urlab.be/"
1616

1717
# Secret string to perform private API calls to incubator.
1818
# Go to [INCUBATOR]/admin/space/privateapikey/ to obtain one

data/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
sudoers.json

ircbot/abstractbot.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@ def reply(self, text, private=False, hilight=False, strip_text=True):
5252
text = self.user + ": " + text
5353
self.bot.say(text, target=target, strip_text=strip_text)
5454

55-
5655
class AbstractBot:
5756
"""
5857
Base class for all bots backends. Define the common behaviour for the bot,
@@ -99,7 +98,7 @@ def __init__(
9998
:type local_only: bool
10099
101100
:example:
102-
>>> Bot("Bot", {'#chan': AwesomePlugin()})
101+
>>> Bot("Bot", {'#chan': [AwesomePlugin()]})
103102
"""
104103
self.main_chan = main_chan
105104
self.nickname = nickname
@@ -118,6 +117,7 @@ def __init__(
118117
chans[chan][k] = chans[chan].get(k, []) + list(v)
119118
self.channels = chans
120119
self.log = logging.getLogger(__name__)
120+
121121

122122
def spawn(self, maybe_coroutine):
123123
"""
@@ -141,7 +141,7 @@ def connect(self, **kwargs):
141141
self.spawn(callback())
142142
return self
143143

144-
def feed(self, user, target, text):
144+
def feed(self, user, target, text, sudo=False):
145145
"""
146146
Feed a new message into the bot
147147
@@ -155,18 +155,27 @@ def feed(self, user, target, text):
155155
# First check if the message was sent over a bridge by a bot.
156156
# If this is the case, extract the original author and text that was
157157
# sent on the other side of the bridge, and use them as user and text
158+
158159
if user in self.bridge_bots:
159-
match = re.match(r"^\s*<\s*([^>]+)\s*>\s*(.+)", text)
160+
self.log.debug("msg from bridge")
161+
match = re.match(r"^\s*\[\s*([^>]+)\s*\]\s*(.+)", text)
160162
if match:
163+
self.log.debug("command from bridge" + user)
161164
user = match.group(1)
162165
text = match.group(2)
166+
163167

164168
target = target.lower()
165169
is_query = target[0] == "#"
170+
commands = []
166171
if is_query:
167-
commands = self.channels.get(target, {}).get("commands", [])
172+
channel_callbacks = self.channels.get(target, {})
173+
commands = channel_callbacks.get("commands", [])
174+
if sudo:
175+
commands.extend(channel_callbacks.get("sudo_commands", []))
168176
else:
169177
commands = self.channels.get("query", {}).get("commands", [])
178+
170179
for (pattern, callback) in commands:
171180
match = pattern.match(text)
172181
if match:

ircbot/plugin.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,22 @@ def load(self, bot, chan):
1010
self.chan = chan
1111
callbacks = {
1212
"commands": [],
13+
"sudo_commands": [],
1314
"on_join": [],
1415
"on_connect": [],
1516
}
1617
for member in map(partial(getattr, self), dir(self)):
1718
if hasattr(member, "_botplugin_special_tag_pattern"):
1819
pattern = member._botplugin_special_tag_pattern
19-
callbacks["commands"].append((re.compile(pattern), member))
20+
if hasattr(member, "_need_sudo") and member._need_sudo:
21+
callbacks["sudo_commands"].append((re.compile(pattern), member))
22+
else:
23+
callbacks["commands"].append((re.compile(pattern), member))
2024
elif hasattr(member, "_botplugin_special_tag_onjoin"):
2125
callbacks["on_join"].append(member)
2226
elif hasattr(member, "_botplugin_special_tag_onconnect"):
2327
callbacks["on_connect"].append(member)
28+
2429
callbacks["commands"].sort(key=lambda P: P[1]._special_tag_id)
2530
return callbacks
2631

@@ -31,7 +36,7 @@ def set_topic(self, text):
3136
self.bot.set_topic(text, target=self.chan)
3237

3338
@classmethod
34-
def command(cls, pattern):
39+
def command(cls, pattern, need_sudo=False):
3540
cls.comment_tag_id += 1
3641
# Here's the trick. We keep a static id, which is incremented any time
3742
# we declare a new command, so that we know in which order they have
@@ -41,6 +46,7 @@ def command(cls, pattern):
4146
def wrapper(func):
4247
func._botplugin_special_tag_pattern = pattern
4348
func._special_tag_id = cls.comment_tag_id
49+
func._need_sudo = need_sudo
4450
return func
4551

4652
return wrapper

plugins/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@
1111
from .trump import Trump
1212
from .twitter import Twitter
1313
from .urls import UrlShow
14+
from .sudo import Sudo

plugins/giphy.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@
66
from .helpers import public_api
77

88

9+
910
class Giphy(BotPlugin):
1011
def __init__(self, giphy_key):
1112
self.giphy_key = giphy_key
13+
self.default_gif = "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExbHplbzc4MjQ2MDRjemcxMDZ3dXhvc3N3aTBodW9lcGt6am9iNzYwNyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tHIRLHtNwxpjIFqPdV/giphy.gif"
1214

1315
def clean_url(self, url):
1416
m = re.match(r"^(https://.+/giphy\.gif).*", url)
@@ -20,7 +22,12 @@ async def search_gif(self, query):
2022
url = "http://api.giphy.com/v1/gifs/search?api_key={}&q={}"
2123
q = query.replace(" ", "+")
2224
r = await public_api(url.format(self.giphy_key, q))
23-
chosen = random.choice(r["data"])
25+
gif_data = r["data"]
26+
27+
if not gif_data:
28+
return self.default_gif
29+
30+
chosen = random.choice(gif_data)
2431
return self.clean_url(chosen["images"]["original"]["url"])
2532

2633
@BotPlugin.command(r"\!gif (#[\w\d_-]+) (.+)")

plugins/helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ async def public_api(endpoint):
8888

8989

9090
async def spaceapi():
91-
return public_api(SPACEAPI)
91+
return await public_api(SPACEAPI)
9292

9393

9494
async def full_pamela():

plugins/reminder.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import asyncio
22
import random
3-
from datetime import datetime
3+
from datetime import datetime, timezone
44
from operator import itemgetter
55
from time import time
66

@@ -55,7 +55,7 @@ async def remind_events(self):
5555
Rappelle les évènements proches
5656
"""
5757
events = await public_api("/events/")
58-
now = datetime.now()
58+
now = datetime.now(timezone.utc)
5959

6060
for event in events["results"]:
6161
if not event.get("start", None):

0 commit comments

Comments
 (0)