Merge pull request #23 from dngfx/master

Make tweets say Twitter instead of tweets, and update ducks
This commit is contained in:
jesopo 2018-09-24 12:28:33 +01:00 committed by GitHub
commit 7522b0fae2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 237 additions and 35 deletions

View file

@ -26,6 +26,7 @@ THIRD_COLUMN = list(range(1, 37))[2::3]
REGEX_STREET = re.compile("street([1-9]|1[0-2])$") REGEX_STREET = re.compile("street([1-9]|1[0-2])$")
class Module(object): class Module(object):
def __init__(self, bot, events, exports): def __init__(self, bot, events, exports):
self.bot = bot self.bot = bot
events.on("received.command.coins").hook(self.coins, events.on("received.command.coins").hook(self.coins,
@ -57,6 +58,7 @@ class Module(object):
self.send, min_args=2, help="Send coins to a user", self.send, min_args=2, help="Send coins to a user",
usage="<nickname> <amount>", authenticated=True) usage="<nickname> <amount>", authenticated=True)
now = datetime.datetime.now() now = datetime.datetime.now()
until_next_hour = 60-now.second until_next_hour = 60-now.second
until_next_hour += ((60-(now.minute+1))*60) until_next_hour += ((60-(now.minute+1))*60)
@ -107,8 +109,8 @@ class Module(object):
top_10 = sorted(all_coins.keys()) top_10 = sorted(all_coins.keys())
top_10 = sorted(top_10, key=all_coins.get, reverse=True)[:10] top_10 = sorted(top_10, key=all_coins.get, reverse=True)[:10]
top_10 = ", ".join("%s (%s)" % (Utils.prevent_highlight(event[ top_10 = ", ".join("%s (%s)" % (Utils.prevent_highlight(
"server"].get_user(nickname).nickname), "{0:.2f}".format( event["server"].get_user(nickname).nickname), "{0:.2f}".format(
all_coins[nickname])) for nickname in top_10) all_coins[nickname])) for nickname in top_10)
event["stdout"].write("Richest users: %s" % top_10) event["stdout"].write("Richest users: %s" % top_10)

View file

@ -29,7 +29,8 @@ class Out(object):
].decode("utf8").lstrip()) ].decode("utf8").lstrip())
else: else:
self._text = "" self._text = ""
self.target.send_message(text, prefix="[%s] " % self.prefix()) self.target.send_message(text, prefix=Utils.FONT_RESET + "[%s] " %
self.prefix())
def set_prefix(self, prefix): def set_prefix(self, prefix):
self.module_name = prefix self.module_name = prefix
def has_text(self): def has_text(self):

View file

@ -1,24 +1,42 @@
#--require-config wordnik-api-key #--require-config wordnik-api-key
import Utils import Utils
import time
URL_WORDNIK = "http://api.wordnik.com:80/v4/word.json/%s/definitions" URL_WORDNIK = "https://api.wordnik.com/v4/word.json/%s/definitions"
URL_WORDNIK_RANDOM = "https://api.wordnik.com/v4/words.json/randomWord"
RANDOM_DELAY_SECONDS = 3
class Module(object): class Module(object):
def __init__(self, bot, events, exports): def __init__(self, bot, events, exports):
self.bot = bot self.bot = bot
self.last_called = 0
self.events = events
events.on("received.command.define").hook(self.define, events.on("received.command.define").hook(self.define,
help="Define a provided term", usage="<phrase>") help="Define a provided term", usage="<phrase>")
events.on("received.command.randomword").hook(self.random_word,
help="Generate a random word!")
def get_definition(self, event):
word = event["args"] if "args" in event else event
page = Utils.get_url(URL_WORDNIK % word, get_params={
"useCanonical": "true", "limit": 1,
"sourceDictionaries": "wiktionary", "api_key": self.bot.config[
"wordnik-api-key"]}, json=True)
return page
def define(self, event): def define(self, event):
if event["args"]: if event["args"]:
word = event["args"] word = event["args"]
else: else:
word = event["buffer"].get(from_self=False) word = event["buffer"].get(from_self=False)
page = Utils.get_url(URL_WORDNIK % event["args"], get_params={ page = self.get_definition(event)
"useCanonical": "true", "limit": 1,
"sourceDictionaries": "wiktionary", "api_key": self.bot.config[
"wordnik-api-key"]}, json=True)
if page: if page:
if len(page): if len(page):
event["stdout"].write("%s: %s" % (page[0]["word"], event["stdout"].write("%s: %s" % (page[0]["word"],
@ -27,3 +45,36 @@ class Module(object):
event["stderr"].write("No definitions found") event["stderr"].write("No definitions found")
else: else:
event["stderr"].write("Failed to load results") event["stderr"].write("Failed to load results")
def random_word(self, event):
if not self.last_called or (time.time()-self.last_called >=
RANDOM_DELAY_SECONDS):
self.last_called = time.time()
page = Utils.get_url(URL_WORDNIK_RANDOM, get_params={
"api_key":self.bot.config["wordnik-api-key"],
"min_dictionary_count":1},json=True)
if page:
if len(page):
definition = self.get_definition(page["word"])
if len(definition):
definition = definition[0]
else:
self.events.on("send.stderr").call(module_name="Random",
target=event["target"],
message="Try again in a couple of seconds")
return
event["stdout"].set_prefix("Random")
event["stdout"].write("Random Word: %s - Definition: %s" % (
page["word"], definition["text"]))
else:
event["stderr"].write("Something has gone terribly wrong")
else:
event["stderr"].write("Failed to load results")
else:
self.events.on("send.stderr").call(module_name="Random",
target=event["target"],
message="Try again in a couple of seconds")

View file

@ -23,9 +23,16 @@ class Module(object):
self.events = events self.events = events
events.on("received.command.bef").hook(self.befriend, events.on("received.command.bef").hook(self.befriend,
priority=EventManager.PRIORITY_HIGH, help="Befriend a duck!") priority=EventManager.PRIORITY_HIGH,
help="Befriend a duck!")
events.on("received.command.bang").hook(self.shoot, events.on("received.command.bang").hook(self.shoot,
priority=EventManager.PRIORITY_HIGH, help="Shoot a duck! Meanie.") priority=EventManager.PRIORITY_HIGH,
help="Shoot a duck! Meanie.")
events.on("received.command.decoy").hook(
self.duck_decoy,
priority=EventManager.PRIORITY_HIGH,
help="Lay out a sneaky decoy!")
events.on("received.command.friends").hook(self.duck_friends, events.on("received.command.friends").hook(self.duck_friends,
help="See who the friendliest people to ducks are!") help="See who the friendliest people to ducks are!")
@ -41,10 +48,20 @@ class Module(object):
"help": "Should the bot kick if there's no duck?", "help": "Should the bot kick if there's no duck?",
"validate": Utils.bool_or_none}) "validate": Utils.bool_or_none})
exports.add("channelset", {"setting": "ducks-min-unique",
"help": "Minimum unique users required to "
"talk before a duck spawns.",
"validate": Utils.int_or_none})
exports.add("channelset", {"setting": "ducks-min-messages",
"help": "Minimum messages between ducks "
"spawning.",
"validate": Utils.int_or_none})
events.on("new.channel").hook(self.new_channel) events.on("new.channel").hook(self.new_channel)
events.on("received.message.channel").hook( events.on("received.message.channel").hook(
self.channel_message) self.channel_message, EventManager.PRIORITY_LOW)
for server in self.bot.servers.values(): for server in self.bot.servers.values():
for channel in server.channels.values(): for channel in server.channels.values():
@ -80,27 +97,43 @@ class Module(object):
def clear_ducks(self, channel): def clear_ducks(self, channel):
rand_time = self.generate_next_duck_time() rand_time = self.generate_next_duck_time()
if hasattr(channel.games, "ducks"):
del channel.games["ducks"]
channel.games["ducks"] = {'messages': 0, 'duck_spawned': 0, channel.games["ducks"] = {'messages': 0, 'duck_spawned': 0,
'unique_users': [], 'unique_users': [],
'next_duck_time': rand_time} 'next_duck_time': rand_time,
'decoy_spawned': 0, 'decoy_requested': 0,
'next_decoy_time': rand_time}
def start_game(self, channel): def start_game(self, channel):
# event is immediately the IRCChannel.Channel() event for the current # event is immediately the IRCChannel.Channel() event for the current
# channel # channel
self.clear_ducks(channel) self.clear_ducks(channel)
min_unique = channel.get_setting("ducks-min-unique", 0)
min_messages = channel.get_setting("ducks-min-messages", 0)
if min_unique == 0:
channel.set_setting("ducks-min-unique", DUCK_MINIMUM_UNIQUE)
if min_messages == 0:
channel.set_setting("ducks-min-messages", DUCK_MINIMUM_MESSAGES)
def generate_next_duck_time(self): def generate_next_duck_time(self):
rand_time = random.randint(int(time()) + 360, int(time()) + 1200) rand_time = random.randint(int(time()) + 360, int(time()) + 1200)
return rand_time return rand_time
def is_duck_visible(self, event): def is_duck_visible(self, event, decoy=False):
channel = event["target"] channel = event["target"]
visible = bool(channel.games["ducks"]["duck_spawned"]) visible = channel.games["ducks"]["decoy_spawned"] if \
decoy else channel.games["ducks"]["duck_spawned"]
return visible return visible
def should_kick(self, event): def should_kick(self, event):
channel = event["target"] channel = event["target"]
return channel.get_setting("ducks-kick", False) return channel.get_setting("ducks-kick", False)
def kick_bef(self, event): def kick_bef(self, event):
@ -117,29 +150,53 @@ class Module(object):
channel.send_kick(target, channel.send_kick(target,
"You tried shooting a non-existent duck. Creepy!") "You tried shooting a non-existent duck. Creepy!")
def duck_decoy(self, event):
channel = event["target"]
if self.is_duck_channel(channel) == False:
return
if self.is_duck_visible(event):
return
game = channel.games["ducks"]
game["decoy_requested"] = 1
event.eat()
def should_generate_duck(self, event): def should_generate_duck(self, event):
channel = event["channel"] channel = event["channel"]
game = channel.games["ducks"] game = channel.games["ducks"]
spawned = game["duck_spawned"] spawned = int(game["decoy_spawned"] or game["duck_spawned"])
decoy = bool(game["decoy_requested"])
unique = len(game["unique_users"]) unique = len(game["unique_users"])
messages = game["messages"] messages = game["messages"]
next_duck = game["next_duck_time"] next_duck = game["next_decoy_time"] if decoy else game["next_duck_time"]
min_unique = 1 if decoy else channel.get_setting("ducks-min-unique",
DUCK_MINIMUM_UNIQUE)
min_messages = channel.get_setting("ducks-min-messages", DUCK_MINIMUM_MESSAGES)
requirement = (unique >= min_unique and messages >= min_messages)
# DUCK_MINIMUM_MESSAGES = 10 # DUCK_MINIMUM_MESSAGES = 10
# DUCK_MINIMUM_UNIQUE = 3 # DUCK_MINIMUM_UNIQUE = 3
if spawned == 0 and next_duck < time() and unique >= \ if spawned == 0 and next_duck < time():
DUCK_MINIMUM_UNIQUE and messages >= DUCK_MINIMUM_MESSAGES: if requirement:
return True return True
else:
return False
else: else:
return False return False
def show_duck(self, event): def show_duck(self, event):
channel = event["channel"] channel = event["channel"]
game = channel.games["ducks"]
duck = "" duck = ""
if channel.games["ducks"]["duck_spawned"] == 1: if game["duck_spawned"] == 1 or game["decoy_spawned"] == 1:
return return
duck += DUCK_TAIL duck += DUCK_TAIL
@ -154,7 +211,15 @@ class Module(object):
duck += random.choice(DUCK_MESSAGE) duck += random.choice(DUCK_MESSAGE)
channel.send_message(duck) channel.send_message(duck)
channel.games["ducks"]["duck_spawned"] = 1
# Decoys take priority over regular ducks.
if game["decoy_requested"] == 1:
game["decoy_spawned"] = 1
game["decoy_requested"] = 0
game["next_duck_time"] = self.generate_next_duck_time()
else:
game["duck_spawned"] = 1
def channel_message(self, event): def channel_message(self, event):
if not event["channel"].get_setting("ducks-enabled", False): if not event["channel"].get_setting("ducks-enabled", False):
@ -167,8 +232,8 @@ class Module(object):
user = event["user"] user = event["user"]
game = channel.games["ducks"] game = channel.games["ducks"]
if game["duck_spawned"] == 1 or channel.has_user( if game["decoy_spawned"] == 1 or game["duck_spawned"] == 1 or \
event["user"]) == False: channel.has_user(event["user"]) == False:
return return
unique = game["unique_users"] unique = game["unique_users"]
@ -193,9 +258,12 @@ class Module(object):
if self.is_duck_channel(channel) == False: if self.is_duck_channel(channel) == False:
return return
if self.is_duck_visible(event) == False: if self.is_duck_visible(event, False) == False:
if self.should_kick(event): if self.should_kick(event):
self.kick_bef(event) self.kick_bef(event)
event.eat()
self.clear_ducks(channel)
return return
channel.games["ducks"][ channel.games["ducks"][
@ -214,6 +282,7 @@ class Module(object):
event["stdout"].write(msg) event["stdout"].write(msg)
self.clear_ducks(channel) self.clear_ducks(channel)
event.eat()
def shoot(self, event): def shoot(self, event):
channel = event["target"] channel = event["target"]
@ -224,9 +293,12 @@ class Module(object):
if self.is_duck_channel(channel) == False: if self.is_duck_channel(channel) == False:
return return
if self.is_duck_visible(event) == False: if self.is_duck_visible(event, False) == False:
if self.should_kick(event): if self.should_kick(event):
self.kick_bang(event) self.kick_bang(event)
event.eat()
self.clear_ducks(channel)
return return
channel.games["ducks"][ channel.games["ducks"][
@ -245,6 +317,7 @@ class Module(object):
event["stdout"].write(msg) event["stdout"].write(msg)
self.clear_ducks(channel) self.clear_ducks(channel)
event.eat()
def duck_stats(self, event): def duck_stats(self, event):
user = event["user"] user = event["user"]
@ -285,6 +358,7 @@ class Module(object):
Utils.bold(tf), Utils.bold(cf), Utils.bold(channel)) Utils.bold(tf), Utils.bold(cf), Utils.bold(channel))
event["stdout"].write(Utils.bold(nick) + ": " + msg) event["stdout"].write(Utils.bold(nick) + ": " + msg)
event.eat()
def duck_enemies(self, event): def duck_enemies(self, event):
the_enemy = event["server"].find_all_user_channel_settings("ducks-shot") the_enemy = event["server"].find_all_user_channel_settings("ducks-shot")
@ -318,6 +392,7 @@ class Module(object):
sentence += ", ".join(build) sentence += ", ".join(build)
event["stdout"].write(sentence) event["stdout"].write(sentence)
event.eat()
def duck_friends(self, event): def duck_friends(self, event):
friends = event["server"].find_all_user_channel_settings( friends = event["server"].find_all_user_channel_settings(
@ -353,3 +428,4 @@ class Module(object):
sentence += ", ".join(build) sentence += ", ".join(build)
event["stdout"].write(sentence) event["stdout"].write(sentence)
event.eat()

View file

@ -1,12 +1,15 @@
#--require-config lastfm-api-key #--require-config lastfm-api-key
import Utils import Utils
from datetime import datetime, timezone
URL_SCROBBLER = "http://ws.audioscrobbler.com/2.0/" URL_SCROBBLER = "http://ws.audioscrobbler.com/2.0/"
class Module(object): class Module(object):
_name = "last.fm"
def __init__(self, bot, events, exports): def __init__(self, bot, events, exports):
self.bot = bot self.bot = bot
self.events = events
exports.add("set", {"setting": "lastfm", exports.add("set", {"setting": "lastfm",
"help": "Set username on last.fm"}) "help": "Set username on last.fm"})
@ -34,6 +37,24 @@ class Module(object):
track_name = now_playing["name"] track_name = now_playing["name"]
artist = now_playing["artist"]["#text"] artist = now_playing["artist"]["#text"]
if '@attr' in now_playing:
np = True
else:
played = int(now_playing["date"]["uts"])
dts = int(datetime.now(tz=timezone.utc).timestamp())
np = bool((dts - played) < 120)
time_language = "is listening to" if np else "last " \
+ "listened to"
ytquery = " - ".join([artist, track_name])
short_url = self.events.on(
"get.searchyoutube").call_for_result(
query=ytquery)
short_url = " -- " + short_url if short_url else ""
info_page = Utils.get_url(URL_SCROBBLER, get_params={ info_page = Utils.get_url(URL_SCROBBLER, get_params={
"method": "track.getInfo", "artist": artist, "method": "track.getInfo", "artist": artist,
"track": track_name, "autocorrect": "1", "track": track_name, "autocorrect": "1",
@ -55,8 +76,11 @@ class Module(object):
"s" if play_count > 1 else "") "s" if play_count > 1 else "")
event["stdout"].write( event["stdout"].write(
"%s is now playing: %s - %s%s%s" % ( "%s %s: %s - %s%s%s%s" % (
shown_username, artist, track_name, play_count, tags)) shown_username, time_language, artist, track_name,
play_count,
tags,
short_url))
else: else:
event["stderr"].write( event["stderr"].write(
"The user '%s' has never scrobbled before" % ( "The user '%s' has never scrobbled before" % (

View file

@ -3,16 +3,23 @@
class Module(object): class Module(object):
def __init__(self, bot, events, exports): def __init__(self, bot, events, exports):
self.bot = bot self.bot = bot
self.module_name = False
self.silent = False
events.on("received.command.loadmodule").hook(self.load, events.on("received.command.loadmodule").hook(self.load,
min_args=1, permission="load-module", help="Load a module", min_args=1, permission="load-module", help="Load a module",
usage="<module-name>") usage="<module-name>")
events.on("received.command.unloadmodule").hook(self.unload, events.on("received.command.unloadmodule").hook(self.unload,
min_args=1, permission="unload-module", help="Unload a module", min_args=1, permission="unload-module", help="Unload a module",
usage="<module-name>") usage="<module-name>")
events.on("received.command.reloadmodule").hook(self.reload, events.on("received.command.reloadmodule").hook(self.reload,
min_args=1, permission="reload-module", help="Reload a module", min_args=1, permission="reload-module", help="Reoad a module",
usage="<module-name>") usage="<module-name>")
events.on("received.command.reloadallmodules").hook(self.reload_all,
permission="reload-module", help="Reload all modules")
events.on("received.command.enablemodule").hook(self.enable, events.on("received.command.enablemodule").hook(self.enable,
min_args=1, permission="enable-module", help="Enable a module", min_args=1, permission="enable-module", help="Enable a module",
usage="<module-name>") usage="<module-name>")
@ -37,13 +44,35 @@ class Module(object):
event["stdout"].write("Unloaded '%s'" % name) event["stdout"].write("Unloaded '%s'" % name)
def reload(self, event): def reload(self, event):
name = event["args_split"][0].lower() name = self.module_name if self.module_name != False else event[
"args_split"][0].lower()
if not name in self.bot.modules.modules: if not name in self.bot.modules.modules:
event["stderr"].write("Module '%s' isn't loaded" % name) if self.silent == False:
event["stderr"].write("Module '%s' isn't loaded" % name)
return return
self.bot.modules.unload_module(name) self.bot.modules.unload_module(name)
self.bot.modules.load_module(name) self.bot.modules.load_module(name)
event["stdout"].write("Reloaded '%s'" % name)
if self.silent == False:
event["stdout"].write("Reloaded '%s'" % name)
def reload_all(self, event):
modules_reloaded = []
self.silent = True
for name, value in self.bot.modules.modules.items():
if name in modules_reloaded:
pass
self.module_name = name
self.reload(event)
modules_reloaded.append(name)
event["stdout"].write("Reloaded modules: %s" % \
" ".join(modules_reloaded))
self.silent = False
self.module_name = False
def enable(self, event): def enable(self, event):
name = event["args_split"][0].lower() name = event["args_split"][0].lower()

View file

@ -177,7 +177,7 @@ class Module(object):
target, registered, permissions = self._get_user_details( target, registered, permissions = self._get_user_details(
event["server"], event["args_split"][0]) event["server"], event["args_split"][0])
if not registered: if target.identified_account == None:
event["stderr"].write("%s isn't registered" % target.nickname) event["stderr"].write("%s isn't registered" % target.nickname)
return return
@ -194,12 +194,12 @@ class Module(object):
target, registered, permissions = self._get_user_details( target, registered, permissions = self._get_user_details(
event["server"], event["args_split"][0]) event["server"], event["args_split"][0])
if not registered: if target.identified_account == None:
event["stderr"].write("%s isn't registered" % target.nickname) event["stderr"].write("%s isn't registered" % target.nickname)
return return
if not permission in permissions: if permission not in permissions:
event["stderr"].write("%s already has permission '%s'" % ( event["stderr"].write("%s doesn't have permission '%s'" % (
target.nickname, permission)) target.nickname, permission))
else: else:
permissions.remove(permission) permissions.remove(permission)

View file

@ -11,6 +11,7 @@ REGEX_TWITTERURL = re.compile(
"https?://(?:www\.)?twitter.com/[^/]+/status/(\d+)", re.I) "https?://(?:www\.)?twitter.com/[^/]+/status/(\d+)", re.I)
class Module(object): class Module(object):
_name = "Twitter"
def __init__(self, bot, events, exports): def __init__(self, bot, events, exports):
self.bot = bot self.bot = bot
self.events = events self.events = events

View file

@ -24,6 +24,8 @@ class Module(object):
help="Find a video on youtube", usage="[query]") help="Find a video on youtube", usage="[query]")
events.on("received.message.channel").hook(self.channel_message) events.on("received.message.channel").hook(self.channel_message)
events.on("get.searchyoutube").hook(self.search_video)
exports.add("channelset", {"setting": "auto-youtube", exports.add("channelset", {"setting": "auto-youtube",
"help": "Disable/Enable automatically getting info from " "help": "Disable/Enable automatically getting info from "
"youtube URLs", "validate": Utils.bool_or_none}) "youtube URLs", "validate": Utils.bool_or_none})
@ -63,6 +65,22 @@ class Module(object):
video_title, video_duration, video_uploader, "{:,}".format( video_title, video_duration, video_uploader, "{:,}".format(
int(video_views)), video_opinions, URL_YOUTUBESHORT % video_id) int(video_views)), video_opinions, URL_YOUTUBESHORT % video_id)
def search_video(self, event):
search = event["query"]
video_id = ""
search_page = Utils.get_url(URL_YOUTUBESEARCH,
get_params={"q": search, "part": "snippet",
"maxResults": "1", "type": "video",
"key": self.bot.config["google-api-key"]},
json=True)
if search_page:
if search_page["pageInfo"]["totalResults"] > 0:
video_id = search_page["items"][0]["id"]["videoId"]
return "https://youtu.be/%s" % video_id
def yt(self, event): def yt(self, event):
video_id = None video_id = None
search = None search = None