From 0181e68df2f0949ccc9f1af823cd9331408387e6 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Sun, 9 Apr 2017 15:40:57 -0700 Subject: [PATCH 01/23] created testing.json for testing, updated .gitignore, updated some commands, handled permissions for announcments --- .gitignore | 10 ++++++++++ main.py | 35 ++++++++++++++++++++++++++++------- settings.json | 3 ++- 3 files changed, 40 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index b41d147..f9649f5 100644 --- a/.gitignore +++ b/.gitignore @@ -61,3 +61,13 @@ target/ #Ipython Notebook .ipynb_checkpoints + +# Keep git from pushing `settings.json`s with keys/tokens while keeping +# default settings.json format +testing.json + +# Keep pycharm files out of repo +.idea/S.C.S.I..iml +.idea/misc.xml +.idea/modules.xml +.idea/workspace.xml diff --git a/main.py b/main.py index be9bf59..9fdbaf6 100644 --- a/main.py +++ b/main.py @@ -18,7 +18,12 @@ reminders = [] polls = [] -settings = open('settings.json', 'r') +TESTING = True +if TESTING: + settings = open('testing.json', 'r') +else: + settings = open('settings.json', 'r') + ds = json.load(settings) prefix = ds['bot']['prefix'] @@ -100,25 +105,41 @@ async def timer(): async def on_channel_delete(channel): server = channel.server.id msg = "Channel {0} has been deleted!".format(channel.mention) - await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts']) + try: + await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts']) + except discord.Forbidden: + msg = "Missing Permissions for announcements!" + await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts']) @bot.event async def on_channel_create(channel): server = channel.server.id msg = "Channel {0} has been created!".format(channel.mention) - await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts']) + try: + await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts']) + except discord.Forbidden: + msg = "Missing Permissions for announcements!" + await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts']) @bot.event async def on_member_join(member): server = member.server.id msg = "New member {0} has joined the server!".format(member.mention) - await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts']) + try: + await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts']) + except discord.Forbidden: + msg = "Missing Permissions for announcements!" + await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts']) @bot.event async def on_member_remove(member): server = member.server.id msg = "Member {0} has left the server!".format(member.name) - await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts']) + try: + await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts']) + except discord.Forbidden: + msg = "Missing Permissions for announcements!" + await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts']) @bot.event async def on_command(command, ctx): @@ -354,9 +375,9 @@ async def who(ctx, user): break if user == None: await bot.say("mention a user!") - msg = "Name: {0}\nID: {1}\nDiscriminator: {2}\nBot: {3}\nAvatar URL: {4}\nCreated: {5}\nNickname: {6}".format(user.name, user.id, user.discriminator, user.bot, user.avatar_url, user.created_at, user.display_name) - await bot.say(msg) + msg = "```Name: {0}\nID: {1}\nDiscriminator: {2}\nBot: {3}\nCreated: {5}\nNickname: {6}```Avatar URL: {4}\n".format(user.name, user.id, user.discriminator, user.bot, user.avatar_url, user.created_at, user.display_name) await bot.say(str(user)) + await bot.say(msg) except: await bot.say("Please mention a user!") diff --git a/settings.json b/settings.json index f55c47d..1c256d4 100644 --- a/settings.json +++ b/settings.json @@ -21,7 +21,8 @@ "id":"SERVER ID", "announcements":"CHANNEL ID", "poll":"", - "adminLog":"" + "adminLog":"", + "botspam":"" } ] From 4e2c42c6b6e06a60ef4a35ed297531cb142dead0 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Sun, 9 Apr 2017 15:57:40 -0700 Subject: [PATCH 02/23] changed `change_game(...)` to `change_presence(...)` --- main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 9fdbaf6..ddd7a51 100644 --- a/main.py +++ b/main.py @@ -254,7 +254,7 @@ async def changegame(ctx, *game): author = ctx.message.author if checkRole(author, ds['bot']['botmin']): gameName = ' '.join(game) - await bot.change_status(game=discord.Game(name=gameName)) + await bot.change_presence(game=discord.Game(name=gameName)) await bot.say("Changing game to: \"{0}\"!".format(gameName)) else: await bot.say("User is not {0}, ask a {0} to use this command!".format(ds['bot']['botmin'])) @@ -431,7 +431,7 @@ async def on_ready(): logger.info('Game set to:') logger.info(ds['bot']['game']) logger.info('------') - await bot.change_status(game=discord.Game(name=ds['bot']['game'])) + await bot.change_presence(game=discord.Game(name=ds['bot']['game'])) startTime = time.time() timerTask = loop.create_task(timer()) From 60032c3a074a0762f8a75d6a299fffdbeccd67a5 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Sun, 9 Apr 2017 16:49:40 -0700 Subject: [PATCH 03/23] added `!about` command --- main.py | 8 ++++++++ settings.json | 6 +++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index ddd7a51..009d828 100644 --- a/main.py +++ b/main.py @@ -279,6 +279,14 @@ async def remind(ctx, delay, *message): except ValueError: await bot.say("Incorrect format for the delay") +@bot.command() +async def about(): + try: + msg = "```Version: {0}\nPrefix: {1}\n\"Game\": {2}\nContributors: {3}```".format(ds['bot']['version'], ds['bot']['prefix'], ds['bot']['game'], str(ds['contrib']).strip("[]")) + await bot.say(msg) + except: + pass + @bot.command(pass_context=True) async def backup(ctx, num="1000"): '''Backs up messages in the current channel. "all" will back up the entire channel. If num is not provided, defaults to 1000''' diff --git a/settings.json b/settings.json index 1c256d4..9194eb0 100644 --- a/settings.json +++ b/settings.json @@ -24,6 +24,10 @@ "adminLog":"", "botspam":"" } - ] + ], + "contrib":[ + "jellopudding", + "onionsans." + ] } From 3c2ff83b7a42c8e7289de6088f22cec94d0cf2dd Mon Sep 17 00:00:00 2001 From: jellopudding Date: Sun, 9 Apr 2017 17:16:41 -0700 Subject: [PATCH 04/23] fixed `'User' object has no attribute 'nick'` --- main.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index 009d828..5f8b952 100644 --- a/main.py +++ b/main.py @@ -324,7 +324,7 @@ async def backup(ctx, num="1000"): m = message.clean_content m = newliner.sub('\n\t', m) - f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str(message.author.nick) + '):\n\t' + m + '\n') + f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str(message.author.display_name) + '):\n\t' + m + '\n') f.write('attachments:\n') for a in message.attachments: f.write('\t') @@ -371,6 +371,8 @@ async def backup(ctx, num="1000"): await bot.say('Backup finished') except ValueError: await bot.say('Incorrect number format') + except e: + await bot.send_message() @bot.command(pass_context=True) async def who(ctx, user): From 313a9bd676d2cea0e47f0caf24e26ef2a5f08327 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Sun, 9 Apr 2017 22:57:02 -0700 Subject: [PATCH 05/23] implimented markov! --- main.py | 35 ++++++++++++++++++++++++++++++++- markov.py | 57 +++++++++++++++++++++++++++++++++++++++++++++++++----- vocab.json | 1 + words.json | 1 + 4 files changed, 88 insertions(+), 6 deletions(-) create mode 100644 vocab.json create mode 100644 words.json diff --git a/main.py b/main.py index 5f8b952..aeb3143 100644 --- a/main.py +++ b/main.py @@ -9,12 +9,16 @@ import datetime import re +import markov + from discord.ext import commands from pathlib import Path description = '''An automod bot for auto modding ''' +mark = markov.Markov + reminders = [] polls = [] @@ -150,6 +154,34 @@ async def on_command(command, ctx): else: destination = "#{0.channel.name} ({0.server.name})".format(message) +@bot.group(pass_context = True) +async def markov(ctx): + '''the markov command group''' + if ctx.invoked_subcommand == None: + await bot.say("Must be used with a sub command!") + +@markov.command() +async def read(*text): + '''has the makrkov chain read text''' + try: + mark.readText(" ".join(text)) + await bot.say("Read text!") + except TypeError as e: + print(e) + + +@markov.command() +async def save(): + mark.save(mark) + await bot.say("Saved current vocab!") + +@markov.command() +async def write(n: str = '100'): + n = int(n) + await bot.say("Markov incoming!") + msg = "```" + mark.writeText(n) + "```" + await bot.say(msg) + @bot.command() async def test(): '''Prints a test message''' @@ -389,7 +421,7 @@ async def who(ctx, user): await bot.say(str(user)) await bot.say(msg) except: - await bot.say("Please mention a user!") + await bot.say("Please mention a user!") @asyncio.coroutine async def on_tick(): @@ -447,3 +479,4 @@ async def on_ready(): timerTask = loop.create_task(timer()) bot.run(ds['bot']["token"]) settings.close() +mark.stop() \ No newline at end of file diff --git a/markov.py b/markov.py index 69323fc..e3fd339 100644 --- a/markov.py +++ b/markov.py @@ -1,10 +1,55 @@ import random -#import io -#import json +import io +import json class Markov: + # words = [] + # vocab = {} + # wordsFile = open("words.json", "+w") + # vocabFile = open("vocab.json", "+w") + # def __init__(self): + # self.words = json.load(Markov.wordsFile) + # self.vocab = json.load(Markov.vocabFile) + # + # def readText(self, txt): + # txt = txt.split() + # try: + # for i in range(len(txt) - 1): + # try: + # self.vocab[txt[i]].append(txt[i + 1]) + # except: + # self.vocab[txt[i]] = [txt[i + 1]] + # self.words.append(txt[i]) + # except: + # pass + # + # def writeText(self, n = 100): + # text = [random.choice(self.words)] + # n -= 1 + # try: + # for i in range(n): + # tmp = self.vocab[text[i]] + # text.append(random.choice(tmp)) + # except KeyError: + # return " ".join(text) + # except IndexError as e: + # return e + # return " ".join(text) + # + # def save(self): + # Markov.wordsFile.flush(); + # json.dump(self.words, Markov.wordsFile) + # Markov.vocabFile.flush(); + # json.dump(self.vocab, Markov.vocabFile) + # + # def stop(self): + # self.save(self) + # self.vocabFile.close() + # self.wordsFile.close() + # print("Stopping Markov!") vocab = {} words = [] + def readText(txt): txt = txt.split() for i in range(len(txt) - 1): @@ -13,8 +58,8 @@ def readText(txt): except: Markov.vocab[txt[i]] = [txt[i + 1]] Markov.words.append(txt[i]) - - + + def writeText(n = 100): text = [random.choice(Markov.words)] n -= 1 @@ -24,7 +69,9 @@ def writeText(n = 100): text.append(random.choice(tmp)) except KeyError: print("Just a key error, nothing to see here!") - return " ".join(text) + return " ".join(text) + finally: + return " ".join(text) if __name__ == "__main__": text = """test""" diff --git a/vocab.json b/vocab.json new file mode 100644 index 0000000..a3aa509 --- /dev/null +++ b/vocab.json @@ -0,0 +1 @@ +{"this": ["is"], "is": ["a"], "a": ["test"], "hello": ["world"]} \ No newline at end of file diff --git a/words.json b/words.json new file mode 100644 index 0000000..337b503 --- /dev/null +++ b/words.json @@ -0,0 +1 @@ +["this", "is", "a", "hello"] \ No newline at end of file From afe47c3e8396621151921d174c6f6cd5e2b07eb1 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Sun, 9 Apr 2017 23:21:51 -0700 Subject: [PATCH 06/23] configured markov abit --- main.py | 7 ++++++- markov.py | 27 +++++++++++++++++++++------ vocab.json | 2 +- words.json | 2 +- 4 files changed, 29 insertions(+), 9 deletions(-) diff --git a/main.py b/main.py index aeb3143..6607dd3 100644 --- a/main.py +++ b/main.py @@ -169,10 +169,15 @@ async def read(*text): except TypeError as e: print(e) +@markov.command(pass_contect=True) +async def readChan(ctx, n = "100"): + '''do the same thing as backup but have the markov chain read the channel''' + pass + @markov.command() async def save(): - mark.save(mark) + mark.save() await bot.say("Saved current vocab!") @markov.command() diff --git a/markov.py b/markov.py index e3fd339..d3812dc 100644 --- a/markov.py +++ b/markov.py @@ -3,10 +3,16 @@ import json class Markov: - # words = [] - # vocab = {} - # wordsFile = open("words.json", "+w") - # vocabFile = open("vocab.json", "+w") + try: + wordsFile = open("words.json", "+r") + vocabFile = open("vocab.json", "+r") + words = json.load(wordsFile) + vocab = json.load(vocabFile) + except: + wordsFile = open("words.json", "+w") + vocabFile = open("vocab.json", "+w") + words = [] + vocab = {} # def __init__(self): # self.words = json.load(Markov.wordsFile) # self.vocab = json.load(Markov.vocabFile) @@ -47,8 +53,6 @@ class Markov: # self.vocabFile.close() # self.wordsFile.close() # print("Stopping Markov!") - vocab = {} - words = [] def readText(txt): txt = txt.split() @@ -59,6 +63,12 @@ def readText(txt): Markov.vocab[txt[i]] = [txt[i + 1]] Markov.words.append(txt[i]) + def save(): + Markov.wordsFile.flush() + Markov.vocabFile.flush() + json.dump(Markov.words, Markov.wordsFile) + json.dump(Markov.vocab, Markov.vocabFile) + def writeText(n = 100): text = [random.choice(Markov.words)] @@ -73,6 +83,11 @@ def writeText(n = 100): finally: return " ".join(text) + def stop(): + Markov.save() + Markov.vocabFile.close() + Markov.wordsFile.close() + if __name__ == "__main__": text = """test""" Markov.readText(text) diff --git a/vocab.json b/vocab.json index a3aa509..9e26dfe 100644 --- a/vocab.json +++ b/vocab.json @@ -1 +1 @@ -{"this": ["is"], "is": ["a"], "a": ["test"], "hello": ["world"]} \ No newline at end of file +{} \ No newline at end of file diff --git a/words.json b/words.json index 337b503..0637a08 100644 --- a/words.json +++ b/words.json @@ -1 +1 @@ -["this", "is", "a", "hello"] \ No newline at end of file +[] \ No newline at end of file From d2e4167de272b7e7f765d22b8089db0ed2cd0689 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Wed, 7 Jun 2017 20:25:46 -0700 Subject: [PATCH 07/23] misc changes --- main.py | 2 +- markov.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 6607dd3..320a1c7 100644 --- a/main.py +++ b/main.py @@ -172,7 +172,7 @@ async def read(*text): @markov.command(pass_contect=True) async def readChan(ctx, n = "100"): '''do the same thing as backup but have the markov chain read the channel''' - pass + await bot.say("This feature has not been implemented yet!") @markov.command() diff --git a/markov.py b/markov.py index d3812dc..a561e3d 100644 --- a/markov.py +++ b/markov.py @@ -92,4 +92,4 @@ def stop(): text = """test""" Markov.readText(text) print(Markov.writeText()) -#test +#test \ No newline at end of file From 46fe3484b3d8ad7bfdf8e36fd1807bc3432294bd Mon Sep 17 00:00:00 2001 From: jellopudding Date: Tue, 6 Mar 2018 12:20:06 -0800 Subject: [PATCH 08/23] removed markov commented out shutdown --- main.py | 70 +++++++++++++++------------------------------------------ 1 file changed, 18 insertions(+), 52 deletions(-) diff --git a/main.py b/main.py index 320a1c7..88b9366 100644 --- a/main.py +++ b/main.py @@ -9,16 +9,12 @@ import datetime import re -import markov - from discord.ext import commands from pathlib import Path description = '''An automod bot for auto modding ''' -mark = markov.Markov - reminders = [] polls = [] @@ -154,39 +150,6 @@ async def on_command(command, ctx): else: destination = "#{0.channel.name} ({0.server.name})".format(message) -@bot.group(pass_context = True) -async def markov(ctx): - '''the markov command group''' - if ctx.invoked_subcommand == None: - await bot.say("Must be used with a sub command!") - -@markov.command() -async def read(*text): - '''has the makrkov chain read text''' - try: - mark.readText(" ".join(text)) - await bot.say("Read text!") - except TypeError as e: - print(e) - -@markov.command(pass_contect=True) -async def readChan(ctx, n = "100"): - '''do the same thing as backup but have the markov chain read the channel''' - await bot.say("This feature has not been implemented yet!") - - -@markov.command() -async def save(): - mark.save() - await bot.say("Saved current vocab!") - -@markov.command() -async def write(n: str = '100'): - n = int(n) - await bot.say("Markov incoming!") - msg = "```" + mark.writeText(n) + "```" - await bot.say(msg) - @bot.command() async def test(): '''Prints a test message''' @@ -242,19 +205,19 @@ async def timeto(ticks): except ValueError: await bot.say("Invalid arguments") -@bot.command(pass_context=True) -async def shutdown(ctx): - '''Shuts down the bot''' - author = ctx.message.author - if checkRole(author, ds['bot']['botmin']): - msg = "Shutting down now!" - await bot.say(msg) - timerTask.cancel() - bot.logout() - settings.close() - sys.exit() - else: - await bot.say("User is not {0}, ask a {0} to use this command!".format(ds['bot']['botmin'])) +# @bot.command(pass_context=True) +# async def shutdown(ctx): +# '''Shuts down the bot''' +# author = ctx.message.author +# if checkRole(author, ds['bot']['botmin']): +# msg = "Shutting down now!" +# await bot.say(msg) +# timerTask.cancel() +# bot.logout() +# settings.close() +# bot.close() +# else: +# await bot.say("User is not {0}, ask a {0} to use this command!".format(ds['bot']['botmin'])) @bot.command() async def timeup(): @@ -482,6 +445,9 @@ async def on_ready(): startTime = time.time() timerTask = loop.create_task(timer()) -bot.run(ds['bot']["token"]) +try: + bot.run(ds['bot']["token"]) +except SystemExit: + print('Shutting down!') settings.close() -mark.stop() \ No newline at end of file +sys.exit() \ No newline at end of file From 3255b6d448ffa935f3977369d1a1911596bff71e Mon Sep 17 00:00:00 2001 From: jellopudding Date: Tue, 6 Mar 2018 12:34:58 -0800 Subject: [PATCH 09/23] removed markov commented out shutdown created poll command group --- main.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 88b9366..78cea4c 100644 --- a/main.py +++ b/main.py @@ -150,13 +150,19 @@ async def on_command(command, ctx): else: destination = "#{0.channel.name} ({0.server.name})".format(message) +@bot.group(pass_context=True) +async def poll(ctx): + '''The poll command group''' + if ctx.invoked_subcommand == None: + await bot.say("Must be used with a subcommand!") + @bot.command() async def test(): '''Prints a test message''' await bot.say("HELLO WORLD!") -@bot.command(pass_context=True) -async def poll(ctx, time, description, *options): +@poll.command(pass_context=True) +async def create(ctx, time, description, *options): '''Creates a poll''' pollNum = ds['bot']['pollNum'] ds['bot']['pollNum'] += 1 @@ -173,7 +179,7 @@ async def poll(ctx, time, description, *options): except: await bot.say('Incorrect number format') -@bot.command() +@poll.command() async def vote(number, option): '''Votes on a poll''' try: From 5e767433dd0e19f408982ca699e778b7c370ceab Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 15:43:42 -0700 Subject: [PATCH 10/23] Added newline at end of file Edited spacing a bit --- main.py | 104 ++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 71 insertions(+), 33 deletions(-) diff --git a/main.py b/main.py index 78cea4c..2220229 100644 --- a/main.py +++ b/main.py @@ -41,15 +41,18 @@ logger.info("Starting SCSI {0} using discord.py {1}".format(ds['bot']["version"], discord.__version__)) print("Starting SCSI {0} using discord.py {1}".format(ds['bot']['version'], discord.__version__)) + def findServer(ident): return bot.get_server(ident) + def findChannel(server, channel): '''finds the channel''' for all in ds['servers']: if all['id'] == server: return bot.get_channel(all[channel]) + ## may not get used but I'm just keeping it def findUser(id): users = list(bot.get_all_members()) @@ -59,6 +62,7 @@ def findUser(id): return all return -1 + def checkRole(user, roleRec): '''Checks if the user has the recuired role''' ok = False @@ -67,6 +71,7 @@ def checkRole(user, roleRec): ok = True return ok + def timeToTicks(time): '''converts time into seconds than to ticks''' time = time.lower() @@ -101,6 +106,7 @@ async def timer(): loop.create_task(on_tick()) await asyncio.sleep(ds['bot']['ticklength']) + @bot.event async def on_channel_delete(channel): server = channel.server.id @@ -111,6 +117,7 @@ async def on_channel_delete(channel): msg = "Missing Permissions for announcements!" await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts']) + @bot.event async def on_channel_create(channel): server = channel.server.id @@ -121,6 +128,7 @@ async def on_channel_create(channel): msg = "Missing Permissions for announcements!" await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts']) + @bot.event async def on_member_join(member): server = member.server.id @@ -131,6 +139,7 @@ async def on_member_join(member): msg = "Missing Permissions for announcements!" await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts']) + @bot.event async def on_member_remove(member): server = member.server.id @@ -141,6 +150,7 @@ async def on_member_remove(member): msg = "Missing Permissions for announcements!" await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts']) + @bot.event async def on_command(command, ctx): message = ctx.message @@ -150,16 +160,19 @@ async def on_command(command, ctx): else: destination = "#{0.channel.name} ({0.server.name})".format(message) + @bot.group(pass_context=True) async def poll(ctx): '''The poll command group''' if ctx.invoked_subcommand == None: await bot.say("Must be used with a subcommand!") + @bot.command() async def test(): - '''Prints a test message''' - await bot.say("HELLO WORLD!") + '''Prints a test message''' + await bot.say("HELLO WORLD!") + @poll.command(pass_context=True) async def create(ctx, time, description, *options): @@ -167,18 +180,19 @@ async def create(ctx, time, description, *options): pollNum = ds['bot']['pollNum'] ds['bot']['pollNum'] += 1 try: -## time = int(time) + ## time = int(time) time = timeToTicks(time) desc = description pos = {} server = ctx.message.server.id for all in options: pos[all] = 0 - polls.append({"time":time, 'pollNum':pollNum, "desc":desc, "pos":pos, "server":server}) + polls.append({"time": time, 'pollNum': pollNum, "desc": desc, "pos": pos, "server": server}) await bot.say("New poll created! #{0}, possibilities: {1}".format(pollNum, pos)) except: await bot.say('Incorrect number format') + @poll.command() async def vote(number, option): '''Votes on a poll''' @@ -189,11 +203,12 @@ async def vote(number, option): if all['pollNum'] == pollNum: if pos in all['pos'].keys(): all['pos'][pos] += 1 - break # Why waste valuable processing cycles? + break # Why waste valuable processing cycles? await bot.say('Invalid option for that poll') except ValueError: await bot.say('Incorrect number format') + @bot.command() async def timeto(ticks): '''says how much time will pass in ticks @@ -211,6 +226,7 @@ async def timeto(ticks): except ValueError: await bot.say("Invalid arguments") + # @bot.command(pass_context=True) # async def shutdown(ctx): # '''Shuts down the bot''' @@ -236,9 +252,10 @@ async def timeup(): msg = "Time up is: *{0} Hours, {1} Minutes and, {2} Seconds*".format(hoursUp, minutesUp, timeUp) await bot.say(msg) -#the following code does not work, and so we will not keep it -#@bot.command(pass_context=True) -#async def tts(ctx): + +# the following code does not work, and so we will not keep it +# @bot.command(pass_context=True) +# async def tts(ctx): # '''Turns TTS on or off''' # if ctx.message.content[len(prefix) + 4:] == "on": # ds['bot']['tts'] = True @@ -254,6 +271,7 @@ async def echo(*, message): logger.info('Echoing: {0}'.format(message)) await bot.say(message) + @bot.command(pass_context=True) async def changegame(ctx, *game): '''Changes the game being displayed''' @@ -265,18 +283,19 @@ async def changegame(ctx, *game): else: await bot.say("User is not {0}, ask a {0} to use this command!".format(ds['bot']['botmin'])) + @bot.command(pass_context=True) async def remind(ctx, delay, *message): '''Sets a reminder for several seconds in the future''' msg = ' '.join(message) chan = ctx.message.channel try: -## following code kept for posterity -## delay = int(float(delay) / ds['bot']['ticklength']) -## if delay == 0: -## delay = 1 -## reminders.append([delay, chan, msg]) -## await bot.say("Reminder set") + ## following code kept for posterity + ## delay = int(float(delay) / ds['bot']['ticklength']) + ## if delay == 0: + ## delay = 1 + ## reminders.append([delay, chan, msg]) + ## await bot.say("Reminder set") delay = timeToTicks(delay) if delay == 0: delay = 1 @@ -285,14 +304,19 @@ async def remind(ctx, delay, *message): except ValueError: await bot.say("Incorrect format for the delay") + @bot.command() async def about(): try: - msg = "```Version: {0}\nPrefix: {1}\n\"Game\": {2}\nContributors: {3}```".format(ds['bot']['version'], ds['bot']['prefix'], ds['bot']['game'], str(ds['contrib']).strip("[]")) + msg = "```Version: {0}\nPrefix: {1}\n\"Game\": {2}\nContributors: {3}```".format(ds['bot']['version'], + ds['bot']['prefix'], + ds['bot']['game'], + str(ds['contrib']).strip("[]")) await bot.say(msg) except: pass + @bot.command(pass_context=True) async def backup(ctx, num="1000"): '''Backs up messages in the current channel. "all" will back up the entire channel. If num is not provided, defaults to 1000''' @@ -307,7 +331,7 @@ async def backup(ctx, num="1000"): if not p.exists(): p.mkdir() newliner = re.compile('\n') end = last_backup_time(servPath + chanPath) - + if num.lower() == "all": await bot.send_message(msg.channel, "Starting backup") count = 1000 @@ -317,37 +341,39 @@ async def backup(ctx, num="1000"): # Probably a better way to do this, but I don't know it async for m in bot.logs_from(msg.channel, limit=1): now_time = m.timestamp - + while count == 1000: count = 0 first = True f = open(servPath + chanPath + 'temp', 'w') - + async for message in bot.logs_from(msg.channel, limit=1000, before=now_time, after=end): if first: start_time = message.timestamp first = False - + m = message.clean_content m = newliner.sub('\n\t', m) - f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str(message.author.display_name) + '):\n\t' + m + '\n') + f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str( + message.author.display_name) + '):\n\t' + m + '\n') f.write('attachments:\n') for a in message.attachments: f.write('\t') f.write(a['url']) f.write('\n') f.write('\n') - + now_time = message.timestamp count += 1 total += 1 - + f.close() - Path(servPath + chanPath + 'temp').rename(servPath + chanPath + str(now_time) + ' -- ' + str(start_time) + '.log') + Path(servPath + chanPath + 'temp').rename( + servPath + chanPath + str(now_time) + ' -- ' + str(start_time) + '.log') await bot.say("Backed up " + str(total) + " messages") - + await bot.say("Backup finished") - + else: num = int(num) f = open(servPath + chanPath + 'temp', 'w') @@ -362,24 +388,27 @@ async def backup(ctx, num="1000"): else: m = message.clean_content m = newliner.sub('\n\t', m) - f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str(message.author.nick) + '):\n\t' + m + '\n') + f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str( + message.author.nick) + '):\n\t' + m + '\n') f.write('attachments:\n') for a in message.attachments: f.write('\t') f.write(a['url']) f.write('\n') f.write('\n') - + end_time = message.timestamp - + f.close() - Path(servPath + chanPath + 'temp').rename(servPath + chanPath + str(end_time) + ' -- ' + str(start_time) + '.log') + Path(servPath + chanPath + 'temp').rename( + servPath + chanPath + str(end_time) + ' -- ' + str(start_time) + '.log') await bot.say('Backup finished') except ValueError: await bot.say('Incorrect number format') except e: await bot.send_message() + @bot.command(pass_context=True) async def who(ctx, user): '''Gives info on a mentioned user''' @@ -391,12 +420,14 @@ async def who(ctx, user): break if user == None: await bot.say("mention a user!") - msg = "```Name: {0}\nID: {1}\nDiscriminator: {2}\nBot: {3}\nCreated: {5}\nNickname: {6}```Avatar URL: {4}\n".format(user.name, user.id, user.discriminator, user.bot, user.avatar_url, user.created_at, user.display_name) + msg = "```Name: {0}\nID: {1}\nDiscriminator: {2}\nBot: {3}\nCreated: {5}\nNickname: {6}```Avatar URL: {4}\n".format( + user.name, user.id, user.discriminator, user.bot, user.avatar_url, user.created_at, user.display_name) await bot.say(str(user)) await bot.say(msg) except: await bot.say("Please mention a user!") + @asyncio.coroutine async def on_tick(): for rem in reminders: @@ -414,24 +445,29 @@ async def on_tick(): await bot.send_message(channel, "poll #{0} is now over!".format(poll['pollNum'])) polls.remove(poll) + def last_backup_time(backup_dir): p = Path(backup_dir) last_file = None for f in p.iterdir(): last_file = f - + if last_file is None: return None file_name = str(last_file) split_name = file_name.split('-- ') date_str = split_name[1] return string_to_datetime(date_str) + def string_to_datetime(s): date_and_time = s.split() date = date_and_time[0].split('-') time = date_and_time[1].split(':') seconds_and_micro = time[2].split('.') - return datetime.datetime(year=int(date[0]), month=int(date[1]), day=int(date[2]), hour=int(time[0]), minute=int(time[1]), second=int(seconds_and_micro[0]), microsecond=int(seconds_and_micro[1])) + return datetime.datetime(year=int(date[0]), month=int(date[1]), day=int(date[2]), hour=int(time[0]), + minute=int(time[1]), second=int(seconds_and_micro[0]), + microsecond=int(seconds_and_micro[1])) + @bot.event async def on_ready(): @@ -449,6 +485,7 @@ async def on_ready(): logger.info('------') await bot.change_presence(game=discord.Game(name=ds['bot']['game'])) + startTime = time.time() timerTask = loop.create_task(timer()) try: @@ -456,4 +493,5 @@ async def on_ready(): except SystemExit: print('Shutting down!') settings.close() -sys.exit() \ No newline at end of file +sys.exit() +# EOF error prevention From 4903e21a83e9932f54cf009f04b74671ec1a59bd Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 16:00:53 -0700 Subject: [PATCH 11/23] corrected typo --- main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 2220229..c17ec1a 100644 --- a/main.py +++ b/main.py @@ -180,7 +180,7 @@ async def create(ctx, time, description, *options): pollNum = ds['bot']['pollNum'] ds['bot']['pollNum'] += 1 try: - ## time = int(time) + # time = int(time) time = timeToTicks(time) desc = description pos = {} @@ -212,7 +212,7 @@ async def vote(number, option): @bot.command() async def timeto(ticks): '''says how much time will pass in ticks - !!obsolite!!''' + !!obsolete!!''' try: ticks = int(''.join(ticks)) seconds = ds['bot']['ticklength'] * ticks From eca47337f05c96ea3f308f4e2d1b71e53eee3b2f Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 16:31:57 -0700 Subject: [PATCH 12/23] reimplemented markov! --- main.py | 21 +++++++ markov.py | 169 +++++++++++++++++++++++++------------------------- settings.json | 2 +- vocab.json | 25 +++++++- words.json | 11 +++- 5 files changed, 142 insertions(+), 86 deletions(-) diff --git a/main.py b/main.py index c17ec1a..eb397ca 100644 --- a/main.py +++ b/main.py @@ -8,6 +8,7 @@ import random import datetime import re +import markov as mk from discord.ext import commands from pathlib import Path @@ -15,6 +16,8 @@ description = '''An automod bot for auto modding ''' +mk = mk.Markov + reminders = [] polls = [] @@ -427,6 +430,23 @@ async def who(ctx, user): except: await bot.say("Please mention a user!") +@bot.group(pass_context=True) +async def markov(ctx): + '''The Markov command group''' + if ctx.invoked_subcommand == None: + await bot.say("Must be used with a subcommand!") + +@markov.command() +async def read(text): + '''Reads passed text''' + mk.readText(text) + await bot.say("Got it!") + +@markov.command() +async def write(words=100): + '''Think, swine!''' + await bot.say("Lucky: {0}".format(mk.writeText(words))) + @asyncio.coroutine async def on_tick(): @@ -493,5 +513,6 @@ async def on_ready(): except SystemExit: print('Shutting down!') settings.close() +mk.stop() sys.exit() # EOF error prevention diff --git a/markov.py b/markov.py index a561e3d..b6a4166 100644 --- a/markov.py +++ b/markov.py @@ -2,94 +2,97 @@ import io import json + class Markov: - try: - wordsFile = open("words.json", "+r") - vocabFile = open("vocab.json", "+r") - words = json.load(wordsFile) - vocab = json.load(vocabFile) - except: - wordsFile = open("words.json", "+w") - vocabFile = open("vocab.json", "+w") - words = [] - vocab = {} - # def __init__(self): - # self.words = json.load(Markov.wordsFile) - # self.vocab = json.load(Markov.vocabFile) - # - # def readText(self, txt): - # txt = txt.split() - # try: - # for i in range(len(txt) - 1): - # try: - # self.vocab[txt[i]].append(txt[i + 1]) - # except: - # self.vocab[txt[i]] = [txt[i + 1]] - # self.words.append(txt[i]) - # except: - # pass - # - # def writeText(self, n = 100): - # text = [random.choice(self.words)] - # n -= 1 - # try: - # for i in range(n): - # tmp = self.vocab[text[i]] - # text.append(random.choice(tmp)) - # except KeyError: - # return " ".join(text) - # except IndexError as e: - # return e - # return " ".join(text) - # - # def save(self): - # Markov.wordsFile.flush(); - # json.dump(self.words, Markov.wordsFile) - # Markov.vocabFile.flush(); - # json.dump(self.vocab, Markov.vocabFile) - # - # def stop(self): - # self.save(self) - # self.vocabFile.close() - # self.wordsFile.close() - # print("Stopping Markov!") + try: + wordsFile = open("words.json", "+r") + vocabFile = open("vocab.json", "+r") + words = json.load(wordsFile) + vocab = json.load(vocabFile) + except: + wordsFile = open("words.json", "+w") + vocabFile = open("vocab.json", "+w") + words = [] + vocab = {} + + # def __init__(self): + # self.words = json.load(Markov.wordsFile) + # self.vocab = json.load(Markov.vocabFile) + # + # def readText(self, txt): + # txt = txt.split() + # try: + # for i in range(len(txt) - 1): + # try: + # self.vocab[txt[i]].append(txt[i + 1]) + # except: + # self.vocab[txt[i]] = [txt[i + 1]] + # self.words.append(txt[i]) + # except: + # pass + # + # def writeText(self, n = 100): + # text = [random.choice(self.words)] + # n -= 1 + # try: + # for i in range(n): + # tmp = self.vocab[text[i]] + # text.append(random.choice(tmp)) + # except KeyError: + # return " ".join(text) + # except IndexError as e: + # return e + # return " ".join(text) + # + # def save(self): + # Markov.wordsFile.flush(); + # json.dump(self.words, Markov.wordsFile) + # Markov.vocabFile.flush(); + # json.dump(self.vocab, Markov.vocabFile) + # + # def stop(self): + # self.save(self) + # self.vocabFile.close() + # self.wordsFile.close() + # print("Stopping Markov!") - def readText(txt): - txt = txt.split() - for i in range(len(txt) - 1): - try: - Markov.vocab[txt[i]].append(txt[i + 1]) - except: - Markov.vocab[txt[i]] = [txt[i + 1]] - Markov.words.append(txt[i]) + def readText(txt): + txt = txt.split() + for i in range(len(txt) - 1): + try: + Markov.vocab[txt[i]].append(txt[i + 1]) + except: + Markov.vocab[txt[i]] = [txt[i + 1]] + Markov.words.append(txt[i]) - def save(): - Markov.wordsFile.flush() - Markov.vocabFile.flush() - json.dump(Markov.words, Markov.wordsFile) - json.dump(Markov.vocab, Markov.vocabFile) + def save(): + Markov.wordsFile.flush() + Markov.vocabFile.flush() + json.dump(Markov.words, Markov.wordsFile, sort_keys=True, indent=4) + json.dump(Markov.vocab, Markov.vocabFile, sort_keys=True, indent=4) + def writeText(n=100): + text = [random.choice(Markov.words)] + n -= 1 + try: + for i in range(n): + tmp = Markov.vocab[text[i]] + text.append(random.choice(tmp)) + except KeyError: + print("Just a key error, nothing to see here!") + return " ".join(text) + finally: + return " ".join(text) - def writeText(n = 100): - text = [random.choice(Markov.words)] - n -= 1 - try: - for i in range(n): - tmp = Markov.vocab[text[i]] - text.append(random.choice(tmp)) - except KeyError: - print("Just a key error, nothing to see here!") - return " ".join(text) - finally: - return " ".join(text) + def stop(): + Markov.save() + Markov.vocabFile.close() + Markov.wordsFile.close() - def stop(): - Markov.save() - Markov.vocabFile.close() - Markov.wordsFile.close() if __name__ == "__main__": - text = """test""" - Markov.readText(text) - print(Markov.writeText()) -#test \ No newline at end of file + text = """This is a test. a mighty fine test indeed""" + Markov.readText(text) + print(Markov.writeText()) + Markov.stop(); +# test diff --git a/settings.json b/settings.json index 9194eb0..78763c0 100644 --- a/settings.json +++ b/settings.json @@ -1,7 +1,7 @@ { "bot":{ "token":"", - "version":"v0.5", + "version":"v0.6", "tts":false, "prefix":"!", "game":"with entity.human.programmer", diff --git a/vocab.json b/vocab.json index 9e26dfe..da6d793 100644 --- a/vocab.json +++ b/vocab.json @@ -1 +1,24 @@ -{} \ No newline at end of file +{ + "This": [ + "is" + ], + "a": [ + "test.", + "mighty" + ], + "fine": [ + "test" + ], + "is": [ + "a" + ], + "mighty": [ + "fine" + ], + "test": [ + "indeed" + ], + "test.": [ + "a" + ] +} \ No newline at end of file diff --git a/words.json b/words.json index 0637a08..9082660 100644 --- a/words.json +++ b/words.json @@ -1 +1,10 @@ -[] \ No newline at end of file +[ + "This", + "is", + "a", + "test.", + "a", + "mighty", + "fine", + "test" +] \ No newline at end of file From f98498e790a7d776c7bf80d7cbc0d8a0ee917901 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 17:12:14 -0700 Subject: [PATCH 13/23] added readchannel command --- main.py | 12 ++++++++++++ vocab.json | 24 ------------------------ words.json | 10 ---------- 3 files changed, 12 insertions(+), 34 deletions(-) delete mode 100644 vocab.json delete mode 100644 words.json diff --git a/main.py b/main.py index eb397ca..5b38ad1 100644 --- a/main.py +++ b/main.py @@ -430,18 +430,30 @@ async def who(ctx, user): except: await bot.say("Please mention a user!") + @bot.group(pass_context=True) async def markov(ctx): '''The Markov command group''' if ctx.invoked_subcommand == None: await bot.say("Must be used with a subcommand!") + @markov.command() async def read(text): '''Reads passed text''' mk.readText(text) await bot.say("Got it!") + +@markov.command(pass_context=True) +async def readchannel(ctx, msgs=100): + '''reads messages in the channel''' + await bot.say("Reading {0} messages from {1}".format(msgs, ctx.message.channel)) + async for m in bot.logs_from(ctx.message.channel, msgs): + mk.readText(m.content) + await bot.say("Got it!") + + @markov.command() async def write(words=100): '''Think, swine!''' diff --git a/vocab.json b/vocab.json deleted file mode 100644 index da6d793..0000000 --- a/vocab.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "This": [ - "is" - ], - "a": [ - "test.", - "mighty" - ], - "fine": [ - "test" - ], - "is": [ - "a" - ], - "mighty": [ - "fine" - ], - "test": [ - "indeed" - ], - "test.": [ - "a" - ] -} \ No newline at end of file diff --git a/words.json b/words.json deleted file mode 100644 index 9082660..0000000 --- a/words.json +++ /dev/null @@ -1,10 +0,0 @@ -[ - "This", - "is", - "a", - "test.", - "a", - "mighty", - "fine", - "test" -] \ No newline at end of file From 6e1341fa4046788020163700bf6690093c456228 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 19:11:59 -0700 Subject: [PATCH 14/23] made markov save more often --- main.py | 36 +++++++++++++++++++++++++++--------- settings.json | 9 ++++----- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/main.py b/main.py index 5b38ad1..f5465ac 100644 --- a/main.py +++ b/main.py @@ -18,19 +18,26 @@ mk = mk.Markov -reminders = [] -polls = [] - TESTING = True if TESTING: - settings = open('testing.json', 'r') + settings = open('testing.json', '+r') else: - settings = open('settings.json', 'r') + settings = open('settings.json', '+r') ds = json.load(settings) prefix = ds['bot']['prefix'] +if 'reminders' in ds: + reminders = ds['reminders'] +else: + reminders = [] + +if 'polls' in ds: + polls = ds['polls'] +else: + polls = [] + bot = commands.Bot(command_prefix=prefix, description=description) loop = bot.loop @@ -82,7 +89,7 @@ def timeToTicks(time): timeSec = 0 for all in time: if "w" in all or "week" in all or "weeks" in all: - tmp = all.strip('weks') + tmp = all.strip('weeks') timeSec += datetime.timedelta(weeks=int(tmp)).total_seconds() elif "d" in all or "day" in all or "days" in all: tmp = all.strip('days') @@ -238,8 +245,13 @@ async def timeto(ticks): # msg = "Shutting down now!" # await bot.say(msg) # timerTask.cancel() -# bot.logout() +# #settings.flush() +# #ds['reminders'] = reminders +# #ds['polls'] = poll +# #json.dump(ds, settings) # settings.close() +# mk.stop() +# bot.logout() # bot.close() # else: # await bot.say("User is not {0}, ask a {0} to use this command!".format(ds['bot']['botmin'])) @@ -442,6 +454,7 @@ async def markov(ctx): async def read(text): '''Reads passed text''' mk.readText(text) + mk.save() await bot.say("Got it!") @@ -451,6 +464,7 @@ async def readchannel(ctx, msgs=100): await bot.say("Reading {0} messages from {1}".format(msgs, ctx.message.channel)) async for m in bot.logs_from(ctx.message.channel, msgs): mk.readText(m.content) + mk.save() await bot.say("Got it!") @@ -524,7 +538,11 @@ async def on_ready(): bot.run(ds['bot']["token"]) except SystemExit: print('Shutting down!') -settings.close() -mk.stop() + settings.flush() + ds['reminders'] = reminders + ds['polls'] = poll + json.dump(ds, settings) + settings.close() + mk.stop() sys.exit() # EOF error prevention diff --git a/settings.json b/settings.json index 78763c0..7b43584 100644 --- a/settings.json +++ b/settings.json @@ -25,9 +25,8 @@ "botspam":"" } ], - "contrib":[ - "jellopudding", - "onionsans." - ] - + "contrib":[ + "jellopudding", + "onionsans." + ] } From 73625ee0e72faa2be6916532684dd031565d4f71 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 19:43:22 -0700 Subject: [PATCH 15/23] made markov try until the end of the desired length --- main.py | 8 ++++---- markov.py | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index f5465ac..a4e9722 100644 --- a/main.py +++ b/main.py @@ -538,10 +538,10 @@ async def on_ready(): bot.run(ds['bot']["token"]) except SystemExit: print('Shutting down!') - settings.flush() - ds['reminders'] = reminders - ds['polls'] = poll - json.dump(ds, settings) + # settings.flush() + # ds['reminders'] = reminders + # ds['polls'] = poll + # json.dump(ds, settings) settings.close() mk.stop() sys.exit() diff --git a/markov.py b/markov.py index b6a4166..e2aed13 100644 --- a/markov.py +++ b/markov.py @@ -80,6 +80,7 @@ def writeText(n=100): text.append(random.choice(tmp)) except KeyError: print("Just a key error, nothing to see here!") + writeText(n) return " ".join(text) finally: return " ".join(text) From 72f11b5a279f1fb7b7453ba73f3a09bbe2ef21fc Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 19:51:33 -0700 Subject: [PATCH 16/23] made markov try until the end of the desired length --- main.py | 3 ++- markov.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index a4e9722..20e7506 100644 --- a/main.py +++ b/main.py @@ -471,7 +471,8 @@ async def readchannel(ctx, msgs=100): @markov.command() async def write(words=100): '''Think, swine!''' - await bot.say("Lucky: {0}".format(mk.writeText(words))) + msg = mk.writeText(words) + await bot.say("Lucky: {0}".format(msg)) @asyncio.coroutine diff --git a/markov.py b/markov.py index e2aed13..e00264e 100644 --- a/markov.py +++ b/markov.py @@ -78,9 +78,10 @@ def writeText(n=100): for i in range(n): tmp = Markov.vocab[text[i]] text.append(random.choice(tmp)) + n -= 1 except KeyError: print("Just a key error, nothing to see here!") - writeText(n) + text.append(Markov.writeText(n)) return " ".join(text) finally: return " ".join(text) From 9ff58cfaa8150515b86a954deef7053cfbb4f2eb Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 20:26:46 -0700 Subject: [PATCH 17/23] allowed markov to read channels other then the one called --- main.py | 12 ++++++++---- markov.py | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index 20e7506..791b375 100644 --- a/main.py +++ b/main.py @@ -459,11 +459,15 @@ async def read(text): @markov.command(pass_context=True) -async def readchannel(ctx, msgs=100): +async def readchannel(ctx, msgs=1000): '''reads messages in the channel''' - await bot.say("Reading {0} messages from {1}".format(msgs, ctx.message.channel)) - async for m in bot.logs_from(ctx.message.channel, msgs): - mk.readText(m.content) + if ctx.message.channel_mentions: + channel = ctx.message.channel_mentions[0] + else: + channel = ctx.message.channel + await bot.say("Reading {0} messages from {1}".format(msgs, channel)) + async for m in bot.logs_from(channel, msgs): + mk.readText(m.clean_content) mk.save() await bot.say("Got it!") diff --git a/markov.py b/markov.py index e00264e..651bae4 100644 --- a/markov.py +++ b/markov.py @@ -58,6 +58,7 @@ class Markov: def readText(txt): txt = txt.split() + txt.append('\n') for i in range(len(txt) - 1): try: Markov.vocab[txt[i]].append(txt[i + 1]) From 09350a92b5c3569cd8386d3fc3a341c861afeeba Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 20:46:38 -0700 Subject: [PATCH 18/23] made the bot not read its own messages --- main.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index 791b375..8b7ef60 100644 --- a/main.py +++ b/main.py @@ -467,7 +467,8 @@ async def readchannel(ctx, msgs=1000): channel = ctx.message.channel await bot.say("Reading {0} messages from {1}".format(msgs, channel)) async for m in bot.logs_from(channel, msgs): - mk.readText(m.clean_content) + if m.author != bot.user: + mk.readText(m.clean_content) mk.save() await bot.say("Got it!") @@ -478,6 +479,14 @@ async def write(words=100): msg = mk.writeText(words) await bot.say("Lucky: {0}".format(msg)) +# @markov.command(pass_context=True) +# async def upload(ctx): +# '''uploads the jsons for markov''' +# await mk.save() +# await bot.say("Uploading files!") +# await bot.send_file(ctx.message.channel, mk.vocabFile) +# await bot.send_file(ctx.message.channel, mk.wordsFile) + @asyncio.coroutine async def on_tick(): From 4979602dadb2ce2696c57393c25aae0b02f3932f Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 20:58:07 -0700 Subject: [PATCH 19/23] added vocab.json and words.json to .gitignore --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index f9649f5..9c57510 100644 --- a/.gitignore +++ b/.gitignore @@ -65,6 +65,8 @@ target/ # Keep git from pushing `settings.json`s with keys/tokens while keeping # default settings.json format testing.json +vocab.json +words.json # Keep pycharm files out of repo .idea/S.C.S.I..iml From 6ab65246c1d762282fda36f2a585ce11f3d1476a Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 22:22:49 -0700 Subject: [PATCH 20/23] fixed message length stuff --- main.py | 6 +++++- markov.py | 21 ++++++++------------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/main.py b/main.py index 8b7ef60..4f2e002 100644 --- a/main.py +++ b/main.py @@ -477,7 +477,9 @@ async def readchannel(ctx, msgs=1000): async def write(words=100): '''Think, swine!''' msg = mk.writeText(words) - await bot.say("Lucky: {0}".format(msg)) + msgs = list(chunkstring(msg, 1993)) + for all in msgs: + await bot.say("Lucky: {0}".format(msgs)) # @markov.command(pass_context=True) # async def upload(ctx): @@ -518,6 +520,8 @@ def last_backup_time(backup_dir): date_str = split_name[1] return string_to_datetime(date_str) +def chunkstring(string, length): + return (string[0+i:length+i] for i in range(0, len(string), length)) def string_to_datetime(s): date_and_time = s.split() diff --git a/markov.py b/markov.py index 651bae4..58fe8c6 100644 --- a/markov.py +++ b/markov.py @@ -58,7 +58,6 @@ class Markov: def readText(txt): txt = txt.split() - txt.append('\n') for i in range(len(txt) - 1): try: Markov.vocab[txt[i]].append(txt[i + 1]) @@ -69,23 +68,19 @@ def readText(txt): def save(): Markov.wordsFile.flush() Markov.vocabFile.flush() - json.dump(Markov.words, Markov.wordsFile, sort_keys=True, indent=4) - json.dump(Markov.vocab, Markov.vocabFile, sort_keys=True, indent=4) + json.dump(Markov.words, Markov.wordsFile, sort_keys=True) + json.dump(Markov.vocab, Markov.vocabFile, sort_keys=True) def writeText(n=100): text = [random.choice(Markov.words)] n -= 1 - try: - for i in range(n): + for i in range(n): + try: tmp = Markov.vocab[text[i]] - text.append(random.choice(tmp)) - n -= 1 - except KeyError: - print("Just a key error, nothing to see here!") - text.append(Markov.writeText(n)) - return " ".join(text) - finally: - return " ".join(text) + except KeyError: + print("Just a key error, nothing to see here!") + text.append(random.choice(tmp)) + return " ".join(text) def stop(): Markov.save() From c9c45ea48a4fa456152bf470ee0902d533f0f3ef Mon Sep 17 00:00:00 2001 From: jellopudding Date: Thu, 26 Apr 2018 22:34:13 -0700 Subject: [PATCH 21/23] fixed all insied of msgs --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 4f2e002..c5e1411 100644 --- a/main.py +++ b/main.py @@ -479,7 +479,7 @@ async def write(words=100): msg = mk.writeText(words) msgs = list(chunkstring(msg, 1993)) for all in msgs: - await bot.say("Lucky: {0}".format(msgs)) + await bot.say("Lucky: {0}".format(all)) # @markov.command(pass_context=True) # async def upload(ctx): From 2533d7efe5f576cfb02b655d273b5d9bbaecab2c Mon Sep 17 00:00:00 2001 From: jellopudding Date: Fri, 27 Apr 2018 14:57:49 -0700 Subject: [PATCH 22/23] irrelevant changes to default parameters --- main.py | 4 +++- markov.py | 12 ++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/main.py b/main.py index c5e1411..fc9514d 100644 --- a/main.py +++ b/main.py @@ -477,7 +477,8 @@ async def readchannel(ctx, msgs=1000): async def write(words=100): '''Think, swine!''' msg = mk.writeText(words) - msgs = list(chunkstring(msg, 1993)) + msgs = list(chunkstring(msg, 1000)) + print(msgs) for all in msgs: await bot.say("Lucky: {0}".format(all)) @@ -520,6 +521,7 @@ def last_backup_time(backup_dir): date_str = split_name[1] return string_to_datetime(date_str) + def chunkstring(string, length): return (string[0+i:length+i] for i in range(0, len(string), length)) diff --git a/markov.py b/markov.py index 58fe8c6..6e68db8 100644 --- a/markov.py +++ b/markov.py @@ -1,6 +1,7 @@ import random import io import json +import time class Markov: @@ -71,7 +72,8 @@ def save(): json.dump(Markov.words, Markov.wordsFile, sort_keys=True) json.dump(Markov.vocab, Markov.vocabFile, sort_keys=True) - def writeText(n=100): + def writeText(n=10): + print("writing") text = [random.choice(Markov.words)] n -= 1 for i in range(n): @@ -79,6 +81,8 @@ def writeText(n=100): tmp = Markov.vocab[text[i]] except KeyError: print("Just a key error, nothing to see here!") + time.sleep(0.05) + tmp = Markov.vocab[random.choice(Markov.words)] text.append(random.choice(tmp)) return " ".join(text) @@ -89,8 +93,8 @@ def stop(): if __name__ == "__main__": - text = """This is a test. a mighty fine test indeed""" - Markov.readText(text) + Markov.readText("this is a test") + Markov.readText("a mighty fine test indeed") print(Markov.writeText()) - Markov.stop(); + Markov.stop() # test From 6199bbc79b4dff3ae9cba526a83a31f025aa64b6 Mon Sep 17 00:00:00 2001 From: jellopudding Date: Fri, 27 Apr 2018 17:07:26 -0700 Subject: [PATCH 23/23] added newmarkov.py, a better markov then the old one --- main.py | 23 ++++++++++++++------ newmarkov.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 7 deletions(-) create mode 100644 newmarkov.py diff --git a/main.py b/main.py index fc9514d..94efb63 100644 --- a/main.py +++ b/main.py @@ -9,6 +9,7 @@ import datetime import re import markov as mk +import newmarkov from discord.ext import commands from pathlib import Path @@ -17,6 +18,7 @@ ''' mk = mk.Markov +nmk = newmarkov.NewMarkov() TESTING = True if TESTING: @@ -447,14 +449,17 @@ async def who(ctx, user): async def markov(ctx): '''The Markov command group''' if ctx.invoked_subcommand == None: - await bot.say("Must be used with a subcommand!") + words = len(nmk.words) + await bot.say("I know {0} words!\nPlease use a subcommand to use or expand my knowledge!".format(words)) @markov.command() async def read(text): '''Reads passed text''' - mk.readText(text) - mk.save() + # mk.readText(text) + # mk.save() + nmk.read(text) + nmk.save() await bot.say("Got it!") @@ -468,15 +473,18 @@ async def readchannel(ctx, msgs=1000): await bot.say("Reading {0} messages from {1}".format(msgs, channel)) async for m in bot.logs_from(channel, msgs): if m.author != bot.user: - mk.readText(m.clean_content) - mk.save() + # mk.readText(m.clean_content) + nmk.read(m.clean_content) + # mk.save() + nmk.save() await bot.say("Got it!") @markov.command() async def write(words=100): '''Think, swine!''' - msg = mk.writeText(words) + # msg = mk.writeText(words) + msg = nmk.write(words) msgs = list(chunkstring(msg, 1000)) print(msgs) for all in msgs: @@ -563,6 +571,7 @@ async def on_ready(): # ds['polls'] = poll # json.dump(ds, settings) settings.close() - mk.stop() + nmk.save() + nmk.words_file.close() sys.exit() # EOF error prevention diff --git a/newmarkov.py b/newmarkov.py new file mode 100644 index 0000000..a236012 --- /dev/null +++ b/newmarkov.py @@ -0,0 +1,60 @@ +import json +import io +import random +import numpy + + +class NewMarkov: + + def __init__(self): + self.words = {} # {word: {word: prob}} + try: + self.words_file = open("words.json", "+r") + try: + self.words = json.load(self.words_file) + except json.JSONDecodeError: + print("File empty!") + + except FileNotFoundError: + self.words_file = open("words.json", "+w") + + def read(self, text): + txt = text.split() + for i in range(len(txt) - 1): + if txt[i] in self.words: + if txt[i + 1] in self.words[txt[i]]: + self.words[txt[i]][txt[i + 1]] += 1 + else: + self.words[txt[i]][txt[i + 1]] = 1 + else: + self.words[txt[i]] = {} + self.words[txt[i]][txt[i+1]] = 1 + + def write(self, n=10): + text = [random.choice(list(self.words.keys()))] + n -= 1 + for i in range(n): + if text[i] in self.words: + wordlist = list(self.words[text[i]].keys()) + counts = list(self.words[text[i]].values()) + sum = 0 + for all in counts: + sum += all + for i in range(len(counts)): + counts[i] /= sum + word = numpy.random.choice(wordlist, p=counts) + text.append(word) + else: + text.append(random.choice(list(self.words.keys()))) + return " ".join(text) + + def save(self): + self.words_file.flush() + json.dump(self.words, self.words_file) + +if __name__ == "__main__": + mk = NewMarkov() + mk.read("this is a test") + mk.save() + print(mk.write(10)) + mk.words_file.close() \ No newline at end of file