changed bot.say to bot.msg

This commit is contained in:
iou1name 2018-05-25 15:21:18 -04:00
parent 902a57c911
commit 55087c42ed
37 changed files with 96 additions and 113 deletions

View File

@ -7,7 +7,7 @@ TODO:
Fix the movie table
Consider re-adding the following modules: `etymology, ip`
Consider logging
Change `bot.say` to `bot.msg`
Change `bot.msg` to `bot.msg`
Add CTCP responses
More complex versioning
Better readme

17
bot.py
View File

@ -357,14 +357,6 @@ class Fulvia(irc.IRCClient):
irc.IRCClient.msg(self, user, message, length=None)
def say(self, text, recipient, max_messages=None):
"""
For compatibility with most of the sopel modules. Will phase it out
in favor of self.msg eventually.
"""
# TODO: change everything to use bot.msg()
self.msg(recipient, text)
def reply(self, text, dest, reply_to, notice=False):
"""
For compatibility with most of the sopel modules. Will phase it out
@ -432,15 +424,6 @@ class FulviaWrapper():
user = self._trigger.channel
self._bot.msg(user, message, length)
def say(self, message, destination=None, max_messages=1):
"""
If destination is None, it defaults to the channel the message
was received on.
"""
if destination is None:
destination = self._trigger.channel
self._bot.say(message, destination, max_messages)
def reply(self, message, destination=None, reply_to=None, notice=False):
"""
If destination is None, it defaults to the channel the message

View File

@ -115,7 +115,7 @@ def require_privmsg(message=None):
return function(*args, **kwargs)
else:
if message and not callable(message):
bot.say(message)
bot.msg(message)
return _nop
# Hack to allow decorator without parens
if callable(message):
@ -138,7 +138,7 @@ def require_chanmsg(message=None):
return function(*args, **kwargs)
else:
if message and not callable(message):
bot.say(message)
bot.msg(message)
return _nop
# Hack to allow decorator without parens
if callable(message):
@ -168,7 +168,7 @@ def require_privilege(level, message=None):
allowed = channel_privs.get(trigger.nick, 0) >= level
if not allowed:
if message and not callable(message):
bot.say(message)
bot.msg(message)
else:
return function(bot, trigger, *args, **kwargs)
return guarded
@ -188,7 +188,7 @@ def require_admin(message=None):
def guarded(bot, trigger, *args, **kwargs):
if not trigger.admin:
if message and not callable(message):
bot.say(message)
bot.msg(message)
else:
return function(bot, trigger, *args, **kwargs)
return guarded
@ -211,7 +211,7 @@ def require_owner(message=None):
def guarded(bot, trigger, *args, **kwargs):
if not trigger.owner:
if message and not callable(message):
bot.say(message)
bot.msg(message)
else:
return function(bot, trigger, *args, **kwargs)
return guarded

View File

@ -234,7 +234,7 @@ def ascii(bot, trigger):
Downloads an image and converts it to ascii.
"""
if not trigger.group(2):
return bot.say()
return bot.msg()
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("imagePath")
parser.add_argument("-r", "--reverse", action="store_true", help="Reverse.")
@ -246,7 +246,7 @@ def ascii(bot, trigger):
args = parser.parse_args(trigger.group(2).split())
if args.help:
return bot.say(parser.print_help())
return bot.msg(parser.print_help())
if args.color:
args.color = "irc"
@ -260,15 +260,15 @@ def ascii(bot, trigger):
handle_gif(**vars(args))
file = {"file": open("temp.png", "rb")}
res = requests.post("https://uguu.se/api.php?d=upload-tool", files=file)
bot.say(res.text)
bot.msg(res.text)
elif args.brail2:
image = open_image(args.imagePath)
image_ascii = image_to_brail(image)
image_ascii = image_ascii.replace(""," ")
bot.say(image_ascii)
bot.msg(image_ascii)
else:
image_ascii = image_to_ascii(None, **vars(args))
bot.say(image_ascii)
bot.msg(image_ascii)
def brail_char(chunk, threshold):

View File

@ -33,7 +33,7 @@ def message(bot, trigger):
if name in bot.memory["away"]:
print(True)
msg = f"\x0308{name}\x03 is away: \x0311{bot.memory['away'][name]}"
bot.say(msg)
bot.msg(msg)
@hook(True)

View File

@ -33,12 +33,12 @@ def banhe(bot, trigger):
if period > 2592000:
bot.reply("It's too big, Onii-chan.")
if not period or period > 2592000:
return bot.say(f"Banned \x0304{banhee}\x03 for \x0309∞\x03 seconds.")
return bot.msg(f"Banned \x0304{banhee}\x03 for \x0309∞\x03 seconds.")
bot.say(f"Banned \x0304{banhee}\x03 for \x0309{str(period)}\x03 seconds.")
bot.msg(f"Banned \x0304{banhee}\x03 for \x0309{str(period)}\x03 seconds.")
time.sleep(period)
bot.mode(trigger.channel, False, "b", mask=banmask)
bot.say(f"Unbanned \x0304{banhee}\x03")
bot.msg(f"Unbanned \x0304{banhee}\x03")
@require_admin
@ -61,13 +61,13 @@ def banheall(bot, trigger):
if period > 2592000:
bot.reply("It's too big, Onii-chan.")
if not period or period > 2592000:
return bot.say("Banned \x0304them all\x03 for \x0309∞\x03 seconds.")
return bot.msg("Banned \x0304them all\x03 for \x0309∞\x03 seconds.")
bot.say(f"Banned \x0304them all\x03 for \x0309{str(period)}\x03 seconds.")
bot.msg(f"Banned \x0304them all\x03 for \x0309{str(period)}\x03 seconds.")
time.sleep(period)
for nick in bot.channels[trigger.channel].users:
banmask = configureHostMask(nick)
bot.mode(trigger.channel, False, "b", mask=banmask)
bot.say("Unbanned \x0304them all\x03")
bot.msg("Unbanned \x0304them all\x03")

View File

@ -16,4 +16,4 @@ def BQstatus(bot, trigger):
deathdate = "[2017-02-16 00:19:00]"
msg = "Banished Quest status: " + status + "\nTime since death: "
msg += relativeTime(bot.config, datetime.now(), deathdate) + " ago"
bot.say(msg)
bot.msg(msg)

View File

@ -34,7 +34,7 @@ def c(bot, trigger):
def py(bot, trigger):
"""Evaluate a Python expression."""
if not trigger.group(2):
return bot.say("Need an expression to evaluate")
return bot.msg("Need an expression to evaluate")
query = trigger.group(2)
uri = BASE_TUMBOLIA_URI + 'py/'
@ -42,7 +42,7 @@ def py(bot, trigger):
res.raise_for_status()
answer = res.text
if answer:
#bot.say can potentially lead to 3rd party commands triggering.
bot.say(answer)
#bot.msg can potentially lead to 3rd party commands triggering.
bot.msg(answer)
else:
bot.reply('Sorry, no result.')

View File

@ -16,17 +16,17 @@ def generic_countdown(bot, trigger):
"""
text = trigger.group(2)
if not text:
return bot.say("Please use correct format: .countdown 2012 12 21")
return bot.msg("Please use correct format: .countdown 2012 12 21")
text = text.split()
if (len(text) != 3 or not text[0].isdigit() or not text[1].isdigit()
or not text[2].isdigit()):
return bot.say("Please use correct format: .countdown 2012 12 21")
return bot.msg("Please use correct format: .countdown 2012 12 21")
try:
date = datetime(int(text[0]), int(text[1]), int(text[2]))
except:
return bot.say("Please use correct format: .countdown 2012 12 21")
return bot.msg("Please use correct format: .countdown 2012 12 21")
msg = relativeTime(bot.config, datetime.now(), date)
msg += " until " + trigger.group(2)
bot.say(msg)
bot.msg(msg)

View File

@ -9,4 +9,4 @@ from module import commands, example
def echo(bot, trigger):
"""Echos the given string."""
if trigger.group(2):
bot.say(trigger.group(2))
bot.msg(trigger.group(2))

View File

@ -24,4 +24,4 @@ def grog(bot, trigger):
num = random.randint(0, len(data)-1)
if num >= len(data)-1:
num = len(data)-1
bot.say(data[num])
bot.msg(data[num])

View File

@ -51,7 +51,7 @@ def hangman(bot, trigger):
msg = f"{trigger.nick} has started a game of hangman! " \
+ "Use '.hangman [guess]' to guess a letter or the entire word."
bot.msg(msg)
bot.say("".join(bot.memory["hangman"][trigger.channel].blanks))
bot.msg("".join(bot.memory["hangman"][trigger.channel].blanks))
return
if not bot.memory["hangman"].get(trigger.channel):
@ -61,8 +61,8 @@ def hangman(bot, trigger):
if len(trigger.group(2)) > 1:
if trigger.group(2) == bot.memory["hangman"][trigger.channel].word:
bot.say(f"{trigger.nick} has won!")
bot.say(bot.memory["hangman"][trigger.channel].word)
bot.msg(f"{trigger.nick} has won!")
bot.msg(bot.memory["hangman"][trigger.channel].word)
bot.memory["hangman"].pop(trigger.channel)
return
else:
@ -82,8 +82,8 @@ def hangman(bot, trigger):
bot.reply(msg)
if bot.memory["hangman"][trigger.channel].tries <= 0:
bot.say("Game over!")
bot.say(bot.memory['hangman'][trigger.channel].word)
bot.msg("Game over!")
bot.msg(bot.memory['hangman'][trigger.channel].word)
bot.memory["hangman"].pop(trigger.channel)
else:
bot.say("".join(bot.memory["hangman"][trigger.channel].blanks))
bot.msg("".join(bot.memory["hangman"][trigger.channel].blanks))

View File

@ -16,13 +16,13 @@ def lampToggle(bot, trigger):
try:
res = requests.get("http://192.168.1.12/gpio?0=toggle", timeout=10)
except requests.exceptions.ReadTimeout:
return bot.say("Connection error. Timeout reached.")
return bot.msg("Connection error. Timeout reached.")
except requests.exceptions.ConnectionError:
return bot.say("Connection error. Is the unit dead?")
return bot.msg("Connection error. Is the unit dead?")
if res.text[32] == 'L':
bot.say("Lamp is now OFF.")
bot.msg("Lamp is now OFF.")
elif res.text[32] == 'H':
bot.say("Lamp is now ON.")
bot.msg("Lamp is now ON.")
#@module.require_admin
@ -34,10 +34,10 @@ def roomTemp(bot, trigger):
try:
res = requests.get("http://192.168.1.25/", timeout=10)
except requests.exceptions.ReadTimeout:
return bot.say("Connection error. Timeout reached.")
return bot.msg("Connection error. Timeout reached.")
except requests.exceptions.ConnectionError:
return bot.say("Connection error. Is the unit dead?")
bot.say(res.text)
return bot.msg("Connection error. Is the unit dead?")
bot.msg(res.text)
@module.require_admin
@ -48,13 +48,13 @@ def inkWrite(bot, trigger):
"""
text = trigger.replace(".inkwrite ", "")
if not text:
return bot.say("Need something to write.")
return bot.msg("Need something to write.")
try:
res = requests.get(f"http://192.168.1.125:8000/?text={text}",
timeout=10)
except requests.exceptions.ReadTimeout:
return bot.say("Connection error. Timeout reached.")
return bot.msg("Connection error. Timeout reached.")
except requests.exceptions.ConnectionError:
return bot.say("Connection error. Is the unit dead?")
bot.say("Wrote: " + res.text)
return bot.msg("Connection error. Is the unit dead?")
bot.msg("Wrote: " + res.text)

View File

@ -16,7 +16,7 @@ def interactive_shell(bot, trigger):
Starts an interactive IPython console
"""
if bot.memory['iconsole_running']:
return bot.say('Console already running')
return bot.msg('Console already running')
banner1 = 'Fulvia interactive shell (embedded IPython)'
banner2 = '`bot` and `trigger` are available. To exit, type exit'
@ -26,6 +26,6 @@ def interactive_shell(bot, trigger):
exit_msg=exitmsg)
bot.memory['iconsole_running'] = True
bot.say('console started')
bot.msg('console started')
console()
bot.memory['iconsole_running'] = False

View File

@ -24,21 +24,21 @@ def isup(bot, trigger):
res = requests.head(url, timeout=10, verify=True)
except (requests.exceptions.MissingSchema,
requests.exceptions.InvalidSchema):
return bot.say("Missing or invalid schema. Check the URL.")
return bot.msg("Missing or invalid schema. Check the URL.")
except requests.exceptions.ConnectionError:
return bot.say("Connection error. Are you sure this is a real website?")
return bot.msg("Connection error. Are you sure this is a real website?")
except requests.exceptions.InvalidURL:
return bot.say("Invalid URL.")
return bot.msg("Invalid URL.")
except Exception as e:
print(e)
return bot.say("Listen buddy. I don't know what you're doing, but \
return bot.msg("Listen buddy. I don't know what you're doing, but \
you're not doing it right.")
try:
res.raise_for_status()
return bot.say(url + " appears to be working from here.")
return bot.msg(url + " appears to be working from here.")
except requests.exceptions.HTTPError:
return bot.say(url + " looks down from here.")
return bot.msg(url + " looks down from here.")

View File

@ -8,5 +8,5 @@ from module import commands
def googleit(bot, trigger):
"""Let me just... google that for you."""
if not trigger.group(2):
return bot.say('http://google.com/')
bot.say('http://lmgtfy.com/?q=' + trigger.group(2).replace(' ', '+'))
return bot.msg('http://google.com/')
bot.msg('http://lmgtfy.com/?q=' + trigger.group(2).replace(' ', '+'))

View File

@ -88,7 +88,7 @@ def movieInfo(bot, trigger):
msg += "\n\x0310Overview\x03: " + data['overview']
bot.say(msg)
bot.msg(msg)
def phyiscalRelease(word, tmdb_id=None, api_key=None):
@ -171,4 +171,4 @@ def addMovie(bot, trigger):
except IntegrityError:
confirm = f"Error: {movie} is already in the database."
bot.memory['movie_lock'].release()
bot.say(confirm)
bot.msg(confirm)

View File

@ -15,4 +15,4 @@ def pingAll(bot, trigger):
names.remove("Ishd")
if "Ishd2" in names:
names.remove("Ishd2")
bot.say(" ".join(names))
bot.msg(" ".join(names))

View File

@ -158,9 +158,9 @@ periods = '|'.join(scaling.keys())
def remind(bot, trigger):
"""Gives you a reminder in the given amount of time."""
if not trigger.group(2):
return bot.say("Missing arguments for reminder command.")
return bot.msg("Missing arguments for reminder command.")
if trigger.group(3) and not trigger.group(4):
return bot.say("No message given for reminder.")
return bot.msg("No message given for reminder.")
duration = 0
message = filter(None, re.split(f"(\d+(?:\.\d+)? ?(?:(?i) {periods})) ?",
@ -197,9 +197,9 @@ def at(bot, trigger):
clock format only.
"""
if not trigger.group(2):
return bot.say("No arguments given for reminder command.")
return bot.msg("No arguments given for reminder command.")
if trigger.group(3) and not trigger.group(4):
return bot.say("No message given for reminder.")
return bot.msg("No message given for reminder.")
regex = re.compile(r"(\d+):(\d+)(?::(\d+))?(?:UTC([+-]\d+))? (.*)")
match = regex.match(trigger.group(2))
@ -214,7 +214,7 @@ def at(bot, trigger):
try:
tz = int(tz.replace("UTC", ""))
except ValueError:
bot.say("Invalid timezone. Using the bot's current timezone.")
bot.msg("Invalid timezone. Using the bot's current timezone.")
tz = None
if tz:

View File

@ -61,7 +61,7 @@ def resist(bot, trigger):
Displays the color band code of a resistor for the given resistance.
"""
if not trigger.group(2):
return bot.say("Please specify a value")
return bot.msg("Please specify a value")
parser = argparse.ArgumentParser()
parser.add_argument("value", nargs="+")
parser.add_argument("-r", "--reverse", action="store_true")
@ -69,10 +69,10 @@ def resist(bot, trigger):
args = parser.parse_args(trigger.group(2).split())
if args.reverse: # bands-to-value
bot.say(bands_to_value(" ".join(args.value)))
bot.msg(bands_to_value(" ".join(args.value)))
else: # value-to-band
if len(args.value) > 1:
return bot.say("Too many values.")
return bot.msg("Too many values.")
value = args.value[0].lower()
mul = 1
@ -82,8 +82,8 @@ def resist(bot, trigger):
try:
value = float(value) * mul
except ValueError:
return bot.say("Invalid input.")
return bot.say(value_to_band(value, args.num_bands))
return bot.msg("Invalid input.")
return bot.msg(value_to_band(value, args.num_bands))
def value_to_band(value, num_bands=4):

View File

@ -19,4 +19,4 @@ def rundown(bot, trigger):
else:
with open(os.path.join(bot.static, "rundown.txt"), "r") as file:
data = file.read()
bot.say(data)
bot.msg(data)

View File

@ -65,7 +65,7 @@ def scramble(bot, trigger):
msg = f"{trigger.nick} has started a game of scramble! " \
+ "Use '.scramble [guess]' to guess a letter or the entire word."
bot.msg(msg)
bot.say(bot.memory["scramble"][trigger.channel].shuffled)
bot.msg(bot.memory["scramble"][trigger.channel].shuffled)
return
if not bot.memory["scramble"].get(trigger.channel):
@ -75,11 +75,11 @@ def scramble(bot, trigger):
word = bot.memory["scramble"][trigger.channel].word
if isAnagram(bot, word, trigger.group(2)):
bot.say(f"{trigger.nick} has won!")
bot.msg(f"{trigger.nick} has won!")
msg = "Original word: " \
+ bot.memory["scramble"][trigger.channel].word
bot.say(msg)
bot.msg(msg)
bot.memory["scramble"].pop(trigger.channel)
else:
bot.reply("Incorrect.")
bot.say(bot.memory["scramble"][trigger.channel].shuffled)
bot.msg(bot.memory["scramble"][trigger.channel].shuffled)

View File

@ -139,4 +139,4 @@ def findandreplace(bot, trigger):
else:
phrase = f"{trigger.nick} {new_phrase}"
bot.say(phrase)
bot.msg(phrase)

View File

@ -98,7 +98,7 @@ def seen(bot, trigger):
if args.message:
msg += f'\x03 with "\x0308{message}\x03"'
bot.say(msg)
bot.msg(msg)
def dump_seen_db(bot):

View File

@ -17,11 +17,11 @@ def spellcheck(bot, trigger):
return bot.reply("What word?")
word = trigger.group(2)
if " " in word:
return bot.say("One word at a time, please")
return bot.msg("One word at a time, please")
dictionary = enchant.Dict("en_US")
if dictionary.check(word):
bot.say(word + " is spelled correctly")
bot.msg(word + " is spelled correctly")
else:
msg = f"{word} is not spelled correctly. Maybe you want one of " \
+ "these spellings: "

View File

@ -27,7 +27,7 @@ def gettld(bot, trigger):
td = soup.find("td", string=word)
if not td:
return bot.say(f"Unable to find data for TLD: {word}")
return bot.msg(f"Unable to find data for TLD: {word}")
table_headers = [th.string for th in td.parent.parent.find_all("th")]
if None in table_headers:

View File

@ -50,7 +50,7 @@ def addTopic(bot, trigger):
"""
topic = trigger.group(2)
if not topic:
return bot.say("Please be providing a topic sir.")
return bot.msg("Please be providing a topic sir.")
bot.memory['topic_lock'].acquire()
try:
bot.db.execute("INSERT INTO topic (topic, added_by) VALUES(?,?)",
@ -59,4 +59,4 @@ def addTopic(bot, trigger):
except IntegrityError:
confirm = "Error: " + topic + " is already in the database."
bot.memory['topic_lock'].release()
bot.say(confirm)
bot.msg(confirm)

View File

@ -49,7 +49,7 @@ def tr2(bot, trigger):
tr_text, in_lang = translate(args.text, in_lang=args.inlang,
out_lang=args.outlang)
bot.say(f'"{tr_text}" ({in_lang} to {args.outlang})')
bot.msg(f'"{tr_text}" ({in_lang} to {args.outlang})')
@commands('mangle')

View File

@ -38,4 +38,4 @@ def codepoint(bot, trigger):
template = 'U+%s %s (%s)'
else:
template = 'U+%s %s (\xe2\x97\x8c%s)'
bot.say(template % (point, name, arg))
bot.msg(template % (point, name, arg))

View File

@ -17,11 +17,11 @@ def uptime(bot, trigger):
""".uptime - Returns the uptime of Fulvia."""
delta = datetime.timedelta(seconds=round((datetime.datetime.now() -
bot.memory["uptime"]).total_seconds()))
bot.say(f"I've been sitting here for {delta} and I keep going!")
bot.msg(f"I've been sitting here for {delta} and I keep going!")
@commands('updick')
def updick(bot, trigger):
""".updick - Returns the uptime of Fulvia, measured in dicks."""
delta = datetime.datetime.now() - bot.memory["uptime"]
bot.say("8" + "="*delta.days + "D")
bot.msg("8" + "="*delta.days + "D")

View File

@ -50,4 +50,4 @@ def title_auto(bot, trigger):
title = HTMLParser().unescape(title)
title = title.replace("\n","").strip()
hostname = urlparse(url).hostname
bot.say(f"[ \x0310{title} \x03] - \x0304{hostname}")
bot.msg(f"[ \x0310{title} \x03] - \x0304{hostname}")

View File

@ -90,12 +90,12 @@ def watch(bot, trigger):
name = "Anonymous"
if url in bot.memory["watcher"].keys():
return bot.say("Error: I'm already watching that thread.")
return bot.msg("Error: I'm already watching that thread.")
api_url = get_api_url(url)
res = requests.get(api_url, verify=True)
if res.status_code == 404:
return bot.say("404: thread not found")
return bot.msg("404: thread not found")
thread = res.json()
last_post = get_last_post(thread, name)
@ -108,7 +108,7 @@ def watch(bot, trigger):
bot.db.execute("INSERT INTO watcher(api_url, name, last_post, time_since)"
" VALUES(?,?,?,?,?)", (api_url, name, last_post, time_since))
bot.say("[\x0304Watcher\x03] Watching thread: \x0307" + url)
bot.msg("[\x0304Watcher\x03] Watching thread: \x0307" + url)
@commands("unwatch")
@ -122,9 +122,9 @@ def unwatch(bot, trigger):
bot.memory["watcher"][url].stop.set()
bot.memory["watcher"].pop(url)
except KeyError:
return bot.say("Error: I'm not watching that thread.")
return bot.msg("Error: I'm not watching that thread.")
removeThread(bot, get_api_url(url),)
bot.say("[\x0304Watcher\x03] No longer watching: \x0307" + url)
bot.msg("[\x0304Watcher\x03] No longer watching: \x0307" + url)

View File

@ -141,4 +141,4 @@ def weather(bot, trigger):
temp = get_temp(results)
humidity = get_humidity(results)
wind = get_wind(results)
bot.say(u'%s: %s, %s, %s, %s' % (location, cover, temp, humidity, wind))
bot.msg(u'%s: %s, %s, %s, %s' % (location, cover, temp, humidity, wind))

View File

@ -33,7 +33,7 @@ def say_snippet(bot, query, show_url=True):
msg = f'[\x0304WIKIPEDIA\x03] \x0310{page_name}\x03 | \x0312"{snippet}"'
if show_url:
msg = msg + f"\x03 | \x0307https://en.wikipedia.org/wiki/{query}"
bot.say(msg)
bot.msg(msg)
def wiki_snippet(query):

View File

@ -82,7 +82,7 @@ def wiktionary(bot, trigger):
_, definitions = wikt(word)
if not definitions:
return bot.say(f"Couldn't get any definitions for {word}.")
return bot.msg(f"Couldn't get any definitions for {word}.")
result = format(word, definitions)
if len(result) < 150:
@ -92,4 +92,4 @@ def wiktionary(bot, trigger):
if len(result) > 300:
result = result[:295] + '[...]'
bot.say(result)
bot.msg(result)

View File

@ -15,4 +15,4 @@ def willilike(bot, trigger):
@example('.willilike Banished Quest')
def upvote(bot, trigger):
"""An advanced AI that will determine if you like something."""
bot.say(trigger.nick + " upvoted this post!")
bot.msg(trigger.nick + " upvoted this post!")

View File

@ -25,7 +25,7 @@ def wa_command(bot, trigger):
res = wa_query(query, app_id, units)
bot.say(f"[\x0304Wolfram\x03] {res}")
bot.msg(f"[\x0304Wolfram\x03] {res}")
def wa_query(query, app_id, units='nonmetric'):