rewrite yamamura in go (#28)

* rewrite yamamura in go

* add license + keypair + readme
This commit is contained in:
superwhiskers 2019-03-15 12:24:31 -05:00 committed by Pika
parent 6c0162b219
commit f134d72ad8
17 changed files with 568 additions and 957 deletions

7
.gitignore vendored
View file

@ -1,5 +1,4 @@
.vscode/
output.log
config.json
modmail.json
tags.json
yamamura
yamamura.log
vendor/

View file

@ -1,9 +0,0 @@
# Yamamura
### a pretendo-integrated Discord bot by superwhiskers & friends
### instructions:
1. run `python3 -m pip install -U https://github.com/Rapptz/discord.py/archive/rewrite.zip` and ``python3 -m pip install -U aiohttp``
2. clone or download the source
3. get a discord bot token
4. place it in the file
5. run Yamamura with `python3 Yamamura.py`

View file

@ -1,786 +0,0 @@
from discord.ext.commands import Bot
from time import gmtime, strftime
import discord
import time
import json
import re
import string
import aiohttp
# load config file, exit if not found
cfg = None
try:
with open("config.json", "r") as cfgFile:
cfg = json.load(cfgFile)
except FileNotFoundError:
print(
'copy "config.example.json", rename it to "config.json" and edit it before running Yamamura'
)
# check if the modmail file exists
with open("modmail.json", "a+") as mailfile:
mailfile.seek(0)
if mailfile.read() == "":
mailfile.write("[]")
# check if the tags file exists
with open("tags.json", "a+") as tags_file:
tags_file.seek(0)
if tags_file.read() == "":
tags_file.write("{}")
# help msg
helpmsg = f"""```
Yamamura, the Pretendo Discord bot
General:
{cfg["prefix"]}help : Shows this message
{cfg["prefix"]}toggleupdates : Toggles the Updates role
{cfg["prefix"]}authors : Shows the authors of the bot
{cfg["prefix"]}status : Check the status of the offical Pretendo servers
{cfg["prefix"]}toggleelsewhere : Toggles access to elsewhere. be careful!
Tags:
{cfg["prefix"]}tag <name> : Shows a tag's content
{cfg["prefix"]}tag mk/make/create <name> <txt> : Creates a tag (mods only)
{cfg["prefix"]}tag rm/del/remove/delete <name> : Deletes a tag (mods only)
{cfg["prefix"]}tag ls/list : Shows the tags available
Mail:
{cfg["prefix"]}mail send <msg> : Send a message to the mods with msg as message
{cfg["prefix"]}mail compose : Send a message to the mods in-dms (private)
{cfg["prefix"]}mail read : Read mail (mods only)
{cfg["prefix"]}mail readid <id> : Read mail by id (mods only)
{cfg["prefix"]}mail all : Read all mail (mods only)
{cfg["prefix"]}mail clean : Clean mail read by all mods (mods only)
{cfg["prefix"]}mail delete <id> : Delete mail by id (mods only)
```"""
# author message
authors = """```
superwhiskers (@!superwhiskers#3210): bot concept and main developer
Netux (@Netux#2308): certain features and some regex work
Pika (@ThatNerdyPikachu#2849): features, rewrote bot to use newlib, and fixed the bot several times```"""
# currently composing people
composing = []
try:
if cfg:
# get the bot
bot = Bot(
description="Yamamura by superwhiskers & friends",
command_prefix=cfg["prefix"],
max_messages=1000,
)
# useful functions
# log to the message log
def log(str_to_log):
sanitized_str = ''.join(filter(lambda x: x in string.printable, str_to_log))
print(sanitized_str)
with open("output.log", "a", -1, "utf-8-sig") as output:
output.write(str_to_log + "\n")
# return true if user is mod
def is_mod(user):
return user.id in cfg["moderators"]
# parse modmail to text
def parseMail(mail):
# parse a list of mail
if isinstance(mail, list):
# the string to send to Discord
retstr = """Mail:
"""
# loop through the mail list
for x in range(0, len(mail)):
# append the parsed message to the string
retstr += f"""
{mail[x]["id"]} - Sent by {mail[x]["sender"]}```
{mail[x]["message"]}```
"""
# return the string
return retstr
# parse only a single message
else:
# the string to send to Discord
retstr = f"""
{mail["id"]} - Sent by {mail["sender"]}```
{mail["message"]}```
"""
# return the parsed message
return retstr
# get the current modmail
def readmail(mod):
# the current mail
mail = None
# open the modmail file
with open("modmail.json", "r") as mailfile:
mail = json.load(mailfile)
# the unread mail list
unread = []
# add all of the unread mail
for x in mail:
try:
x["readBy"].index(mod)
except ValueError:
unread.append(x)
x["readBy"].append(mod)
# if no mail is unread
if unread == []:
return None
# write the readby
with open("modmail.json", "w") as mailfile:
mailfile.seek(0)
mailfile.write(json.dumps(mail))
mailfile.truncate()
# return the unread mail
return parseMail(unread)
# send modmail
def sendmail(message, sender):
# the current mail
mail = None
# open the modmail file
with open("modmail.json", "r") as mailfile:
mail = json.load(mailfile)
# constructed mail
mailToSend = {}
# construct the message
mailToSend["id"] = str(hash(time.time()))
mailToSend["sender"] = sender
mailToSend["message"] = message
mailToSend["readBy"] = []
# send the message
mail.append(mailToSend)
# write the mail
with open("modmail.json", "w") as mailfile:
mailfile.seek(0)
mailfile.write(json.dumps(mail))
mailfile.truncate()
return "written"
# clean mail
def cleanmail():
# list of moderator's usernames
mods = cfg["moderators"]
# the current mail
mail = None
# open the modmail file
with open("modmail.json", "r") as mailfile:
mail = json.load(mailfile)
# indexes of mail to delete
indexesToDelete = []
# check if all the mods have read the mail
for x in mail:
mailRead = True
for y in range(0, len(mods)):
try:
x["readBy"].index(mods[y])
except ValueError:
mailRead = False
if mailRead:
indexesToDelete.append(mail.index(x))
# then clean from the mail list the indexes to delete
for x in range(0, len(indexesToDelete)):
del mail[indexesToDelete[x]]
# then save the file
with open("modmail.json", "w") as mailfile:
mailfile.seek(0)
mailfile.write(json.dumps(mail))
mailfile.truncate()
return
# delete a specific message
def deletemail(sid):
# the current mail
mail = None
# open the modmail file
with open("modmail.json", "r") as mailfile:
mail = json.load(mailfile)
# search the mail for a specific id
found = False
for x in mail:
if x["id"] == sid:
del mail[mail.index(x)]
found = True
# if we couldn't find the mail
if not found:
return None
# then save the file
with open("modmail.json", "w") as mailfile:
mailfile.seek(0)
mailfile.write(json.dumps(mail))
mailfile.truncate()
# return at the end
return "not none"
# shows all mail
def listall():
# mail variable
mail = None
# open the modmail file and return the contents
with open("modmail.json", "r") as mailfile:
mail = json.load(mailfile)
# this might happen
if mail == []:
return None
# the mail
return parseMail(mail)
# read a specific message
def readsinglemail(sid):
# the current mail
mail = None
# open the modmail file
with open("modmail.json", "r") as mailfile:
mail = json.load(mailfile)
# find the single message
for x in range(0, len(mail)):
if mail[x]["id"] == sid:
message = mail[x]
return parseMail(message)
# return None if not found
return None
# Tag helpers
def get_tags():
with open("tags.json", "r") as tags_file:
return json.load(tags_file)
def get_tag(tag_name):
tags = get_tags()
for name, tag in tags.items():
if name == tag_name:
return tag
return None
def create_tag(name, content):
tags = get_tags()
tags[
name
] = {
# support for future additions
'content': content
}
save_tags(tags)
def delete_tag(name):
tags = get_tags()
del tags[name]
save_tags(tags)
def save_tags(tags):
with open("tags.json", "w") as tags_file:
tags_file.seek(0)
tags_file.write(json.dumps(tags))
tags_file.truncate()
# returns the server the bot is in
def server():
for x in bot.guilds:
return x
# return a channel object by name
def channel(channel_name):
return discord.utils.get(server().channels, name=channel_name)
# returns a role object by name
def role(role_name):
return discord.utils.get(server().roles, name=role_name)
# returns a user object by name
def user(user_name):
return discord.utils.get(server().members, name=user_name)
# checks if a command is at the start of a message
def command(command, msg):
return re.match(
"^" + cfg["prefix"] + command + "(?:\\s+|$)", msg, re.MULTILINE
)
# checks if the specified member has a role
def hasRole(member, role):
hasRole = False
for x in range(0, len(member.roles)):
if role == member.roles[x].name:
hasRole = True
return hasRole
def coo(channel, target_user, response):
target_part = f"{ target_user.mention }, " if target_user is not None else ""
return channel.send(f"Coo, { target_part }{ response }")
def log_message(message, is_edit=False, is_delet=False):
result = f"[{ message.author.name } "
if is_edit:
result += "edited a message "
if is_delet:
result += f"had their message deleted "
result += "in "
if isinstance(message.channel, discord.channel.DMChannel):
result += "a DM with me"
else:
result += message.channel.name
result += f"]: { message.clean_content } [{ strftime('%m/%d/%Y %H:%M:%S', gmtime()) }]"
log(result)
@bot.event
async def on_ready():
# set server var
for x in bot.guilds:
bot.server = x
break
# print some output
print(
f"logged in as: { bot.user.name } (id:{ bot.user.id }) | connected to { str(len(bot.guilds)) } server(s)"
)
print(
f"invite: https://discordapp.com/oauth2/authorize?bot_id={ bot.user.id }&scope=bot&permissions=8"
)
await bot.change_presence(activity=discord.Game(name=cfg["nowplaying"]))
# message handling
# log message edits
@bot.event
async def on_message_edit(prev, msg):
# log-em, and do it on edits too
log_message(msg, is_edit=True)
@bot.event
async def on_message_delete(msg):
# log the deleted message
log_message(msg, is_delet=True)
# log actual messages too
@bot.event
async def on_message(msg):
# log-em
log_message(msg)
# no checkin yourself or the GitHub bot.
if msg.author.bot:
return
game_role = role("uselesslypingme")
if game_role in msg.role_mentions and not game_role in msg.author.roles:
await msg.author.add_roles(game_role)
await coo(msg.channel, msg.author, "welcome to the game.")
# check if the message is sent by a person who is composing
try:
ind = composing.index(msg.author.name)
if isinstance(msg.channel, discord.DMChannel):
del composing[ind]
await coo(
msg.author,
msg.author,
"are you sure you want to send that message? (yes|no)",
)
confirm = await bot.wait_for(
"message",
check=lambda new_msg: m.channel == msg.author.dm_channel
and new_msg.author == msg.author,
)
if confirm.content == "yes" or 'y':
sendmail(msg.content, msg.author.name)
await coo(msg.author, msg.author, "your mail has been sent.")
for m in cfg["moderators"]:
if m not in cfg["modmail_notif_optout"]:
await bot.guilds[0].get_member(m).send(
"New modmail received from {}!\nHere is the content of the message:```{}```".format(
msg.author.name, msg.content
)
)
else:
await coo(
msg.author, msg.author, "your mail has not been sent!"
)
del composing[ind]
except ValueError:
pass
# do you like teapots? dun dun dun dun dunnn....
if "i'm a teapot" in msg.content.lower():
if hasRole(msg.author, "Real Devs"):
await msg.author.remove_roles(role("Real Devs"))
await coo(
msg.channel,
msg.author,
"you no longer have the Real Devs role.",
)
else:
await msg.author.add_roles(role("Real Devs"))
await coo(
msg.channel, msg.author, "you now have the Real Devs role."
)
await msg.delete()
elif msg.channel.id in cfg["voting_channels"]:
# hopefully fixes this not working
await msg.add_reaction(u'\U0001F44D')
await msg.add_reaction(u'\U0001F44E')
# i'd just like to interject for a moment...
elif "linux" in msg.content.lower():
# make sure it is only linux
splitmsg = msg.content.split(" ")
# search for linux
interject = False
for x in range(0, len(splitmsg)):
if splitmsg[x].lower() == "linux":
interject = True
break
# check to see if it is a good place to send it
if msg.channel.id not in cfg["spam_channels"]:
interject = False
# interject
if interject is True:
await msg.channel.send(
f"""I'd just like to interject for a moment, { msg.author.mention }. What you're referring to as Linux, is in fact, GNU/Linux, or as I've recently taken to calling it, GNU plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully functioning GNU system made useful by the GNU corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. Many computer users run a modified version of the GNU system every day, without realizing it. Through a peculiar turn of events, the version of GNU which is widely used today is often called "Linux", and many of its users are not aware that it is basically the GNU system, developed by the GNU Project. There really is a Linux, and these people are using it, but it is just a part of the system they use. Linux is the kernel: the program in the system that allocates the machine's resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. Linux is normally used in combination with the GNU operating system: the whole system is basically GNU with Linux added, or GNU/Linux. All the so-called "Linux" distributions are really distributions of GNU/Linux."""
)
return
elif "reduxredstone" in msg.content.lower():
splitmsg = msg.content.split(" ")
sendgudmeme = False
for x in range(0, len(splitmsg)):
if splitmsg[x].lower() == "reduxredstone":
sendgudmeme = True
break
# check to see if it is a good place to send it
if msg.channel.id not in cfg["spam_channels"]:
sendgudmeme = False
if sendgudmeme is True:
await msg.channel.send(
"Ahh, I remember the great ReduxRedstone incident of 2018. Everyone set their username to ReduxRedstone, which is RedDucks old name.\nhttps://www.youtube.com/user/halolink4\nhttps://www.github.com/ReduxRedstone\n(thank pika for this)"
)
return
# eh ayy?
elif "ay" in msg.content.lower():
# split the message
splitmsg = msg.clean_content.split(" ")
# the part of the string that contains the 'ayy'
msgayy = None
# find the part of the string with 'ayy'
for x in range(0, len(splitmsg)):
if re.match(
r"^ay{1,}$", splitmsg[x].lower(), re.IGNORECASE & re.MULTILINE
):
msgayy = splitmsg[x]
slot = x
break
# if nothing was found, stop the handler
if msgayy is not None:
# replacement string
ret = ""
# regexes don't work at all with this for some reason.
# see commit cfa4e40d53b637132a7d120918aa03c52c04c720 if
# you want to fix it..
for x in range(0, len(msgayy)):
if msgayy[x] == "y":
ret += "o"
elif msgayy[x] == "Y":
ret += "O"
elif msgayy[x] == "a":
ret += "lma"
elif msgayy[x] == "A":
ret += "LMA"
# concatenating the message
fullret = splitmsg
fullret[slot] = ret
fullret = " ".join(fullret)
# if the string is too long,
if len(fullret) > 2000:
# i'm too lazy to implement splicing the message
if len(fullret) > 2000:
await coo(
msg.channel, msg.author, "your message is too long."
)
return
# SEND IT ALREADY!!!
await msg.channel.send(fullret)
# if the first character is the prefix
elif msg.content.startswith(cfg["prefix"]):
# variable telling if the command user is eligible for mod
# commands
mod = is_mod(msg.author)
# prefix + help
if command("help", msg.content):
await msg.author.send(helpmsg)
# prefix + remindme
elif command("toggleupdates", msg.content):
if hasRole(msg.author, "Updates"):
await msg.author.remove_roles(role("Updates"))
await coo(
msg.channel,
msg.author,
"you no longer have the Updates role.",
)
else:
await msg.author.add_roles(role("Updates"))
await coo(
msg.channel, msg.author, "you now have the Updates role."
)
elif command("toggleelsewhere", msg.content):
if hasRole(msg.author, "elsewhere"):
await msg.author.remove_roles(role("elsewhere"))
await coo(
msg.channel,
msg.author,
"you no longer have the elsewhere role. thank god",
)
else:
await msg.author.add_roles(role("elsewhere"))
await coo(
msg.channel,
msg.author,
"you now have the elsewhere role. be careful",
)
# prefix + authors
elif command("authors", msg.content):
await msg.author.send(authors)
# prefix + modmail
elif command("mail", msg.content):
# split the message and get the arguments
args = msg.content.split(" ")[1:]
# this is a subcommand command
if args == []:
await coo(
msg.channel,
msg.author,
"the mail command requires a subcommand.",
)
return
# test for subcommands
# send mail with compose in-dm
if args[0] == "compose":
await coo(
msg.author,
msg.author,
"""send a message right here containing
the message that you want to send to the mods.""",
)
composing.append(msg.author.name)
# send mail with 1st argument as message
elif args[0] == "send":
def dmcheck(m):
return m.channel == msg.author.dm_channel and m.author == msg.author
await coo(
msg.author,
msg.author,
"are you sure you want to send that message? (yes|no)",
)
confirm = await bot.wait_for("message", check=dmcheck)
if confirm.content == "yes" or 'y':
sendmail(" ".join(args[1:]), msg.author.name)
await coo(
msg.author, msg.author, "your mail has been sent."
)
for m in cfg["moderators"]:
await bot.guilds[0].get_member(m).send(
"New modmail received from {}!\nHere is the content of the message:```{}```".format(
msg.author.name, msg.content
)
)
else:
await coo(
msg.author, msg.author, "your mail has not been sent!"
)
for m in cfg["moderators"]:
if m not in cfg["modmail_notif_optout"]:
await bot.guilds[0].get_member(m).send(
"New modmail received from {}!\nHere is the content of the message:```{}```".format(
msg.author.name, " ".join(args[1:])
)
)
# read unread mail
elif args[0] == "read":
if mod:
mail = readmail(msg.author.name)
if mail is None:
await coo(msg.author, msg.author, "you have no mail.")
else:
await msg.author.send(mail)
else:
await coo(msg.channel, msg.author, "you aren't a mod.")
# read a specific message
elif args[0] == "readid":
if mod:
mail = readsinglemail(args[1])
if mail is None:
await coo(
msg.author, msg.author, "no mail found by that id."
)
else:
await msg.author.send(mail)
else:
await coo(msg.channel, msg.author, "you aren't a mod.")
# read all messages
elif args[0] == "all":
if mod:
mail = listall()
if mail is None:
await coo(msg.author, msg.author, "there is no mail.")
else:
await msg.author.send(mail)
else:
await coo(msg.channel, msg.author, "you aren't a mod.")
# clean mail
elif args[0] == "clean":
if mod:
cleanmail()
await coo(msg.author, msg.author, "cleaned mail.")
else:
await coo(msg.channel, msg.author, "you aren't a mod.")
# delete a specific message
elif args[0] == "delete":
if mod is True:
mail = deletemail(args[1])
if mail is None:
await coo(
msg.author,
msg.author,
"couldn't find a message with that id.",
)
else:
await coo(msg.author, msg.author, "deleted message.")
else:
await coo(msg.channel, msg.author, "you aren't a mod.")
# subcommand not found
else:
await coo(
msg.author,
msg.author,
f"{ args[0] } is not a mail command.",
)
# return at the end
return
elif command("tag", msg.content):
args = msg.content.split(" ")[1:]
args_len = len(args)
create_subcmds = ["mk", "make", "create"]
delete_subcmds = ["rm", "del", "remove", "delete"]
list_subcmds = ["ls", "list"]
reserved_words = create_subcmds + delete_subcmds + list_subcmds
if args_len <= 0:
await coo(
msg.channel,
msg.author,
"this command requires more arguments.",
)
else:
subcommand = args[0].lower()
if subcommand in create_subcmds:
if is_mod(msg.author):
if args_len >= 3:
tag_name = args[1]
if tag_name in reserved_words:
await coo(
msg.channel,
msg.author,
"nice try but that's a reserved name.",
)
else:
create_tag(tag_name, " ".join(args[2:]))
await coo(
msg.channel,
msg.author,
f"tag { tag_name } created.",
)
else:
await coo(
msg.channel,
msg.author,
"this command requires you give the tag a name and content.",
)
else:
await coo(
msg.channel,
msg.author,
"only moderators can create tags.",
)
elif subcommand in delete_subcmds:
if is_mod(msg.author):
if args_len >= 2:
tag_name = args[1]
tag = get_tag(tag_name)
if tag:
delete_tag(tag_name)
await coo(
msg.channel,
msg.author,
f"tag { tag_name } deleted.",
)
else:
await coo(
msg.channel,
msg.author,
f"there is no tag \"{ tag_name }\" to delete. Did you misspell the name?",
)
else:
await coo(
msg.channel,
msg.author,
"this command requires you give the tag to delete.",
)
else:
await coo(
msg.channel,
msg.author,
"only moderators can delete tags.",
)
elif subcommand in list_subcmds:
tag_list = get_tags()
tag_list_msg = f"""tags available: ```
{ ", ".join(tag_list) if len(tag_list) > 0 else "<none>" }
```"""
if msg.channel.id in cfg["spam_channels"]:
await coo(msg.channel, None, tag_list_msg)
else:
await coo(msg.author, None, tag_list_msg)
if not isinstance(msg.channel, discord.DMChannel):
await coo(
msg.channel, msg.author, "sent list in DMs"
)
else:
tag = get_tag(args[0])
if tag is None:
await coo(
msg.channel,
msg.author,
f"\"{ args[0] }\" is not a tag or subcommand",
)
else:
await msg.channel.send(tag['content'])
elif command("status", msg.content):
async with aiohttp.ClientSession() as cs:
async with cs.get(
"https://account.pretendo.cc/isthisworking"
) as r:
resp = await r.json(content_type="text/html")
if resp is not None and resp[
"server"
] == "account.nintendo.net":
await coo(
msg.channel,
msg.author,
"the offical Pretendo servers are indeed online!",
)
else:
await coo(
msg.channel,
msg.author,
"the offical Pretendo servers are offline! Oh no...",
)
bot.run(cfg["token"])
# trying to split an image message doesn't work
except ValueError:
pass

View file

@ -1,9 +1,8 @@
{
"token" : "create a bot account at https://discordapp.com/developers/applications/me",
"token" : "token goes here",
"prefix" : ".",
"moderators" : [ user ID ],
"modmail_notif_optout": [ user ID ]
"spam_channels": [ channel ID ],
"voting_channels": [ channel ID ],
"nowplaying" : "playing beta testing"
"moderators" : [ "moderator ids go here" ],
"modmail_notif_optout" : [ ],
"spam_channels" : [ "spam channel ids go here" ],
"voting_channels": [ "voting channel ids go here" ]
}

View file

@ -1,15 +0,0 @@
#
# core/ - the core python files that Yamamura uses
#
# author: superwhiskers
# license: gplv3
#
# directory structure
#
# core/
# - cmd.py: command handling
# - db.py: database-related things
# - utils.py: utilties
#
# place any code you want to run on import here

View file

@ -1,6 +0,0 @@
#
# core/cmd.py - command handling utilities
#
# author: superwhiskers
# license: gplv3
#

View file

@ -1,6 +0,0 @@
#
# core/db.py - database utilities
#
# author: superwhiskers
# license: gplv3
#

View file

@ -1,6 +0,0 @@
#
# core/utils.py - utilities for yama to use
#
# author: superwhiskers
# license: gplv3
#

8
go.mod Normal file
View file

@ -0,0 +1,8 @@
module github.com/superwhiskers/yamamura
require (
github.com/bwmarrin/discordgo v0.19.0
github.com/sirupsen/logrus v1.3.0
github.com/superwhiskers/fennel v0.0.0-20190211044416-35119a6067a4
github.com/superwhiskers/harmony v0.0.0-20180930143517-90dc7e62f9ee
)

31
go.sum Normal file
View file

@ -0,0 +1,31 @@
github.com/bwmarrin/discordgo v0.19.0 h1:kMED/DB0NR1QhRcalb85w0Cu3Ep2OrGAqZH1R5awQiY=
github.com/bwmarrin/discordgo v0.19.0/go.mod h1:O9S4p+ofTFwB02em7jkpkV8M3R0/PUVOwN61zSZ0r4Q=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/klauspost/compress v1.4.0 h1:8nsMz3tWa9SWWPL60G1V6CUsf4lLjWLTNEtibhe8gh8=
github.com/klauspost/compress v1.4.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/cpuid v0.0.0-20180405133222-e7e905edc00e h1:+lIPJOWl+jSiJOc70QXJ07+2eg2Jy2EC7Mi11BWujeM=
github.com/klauspost/cpuid v0.0.0-20180405133222-e7e905edc00e/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME=
github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/superwhiskers/fennel v0.0.0-20190211044416-35119a6067a4 h1:Hn/WZLe1retRbDrvj2g6K9pI449C2vpBJGhVgo89vWM=
github.com/superwhiskers/fennel v0.0.0-20190211044416-35119a6067a4/go.mod h1:ysee5rymgTR5NGfYHbXsh0q69hRg1BIZoRZ9CtmkDaw=
github.com/superwhiskers/harmony v0.0.0-20180930143517-90dc7e62f9ee h1:RnEP6ycC+YMfOnhfPd1BV0ihsycpPaKNrD9y3GFUk1Y=
github.com/superwhiskers/harmony v0.0.0-20180930143517-90dc7e62f9ee/go.mod h1:lEkHPWe//0mZsMxYVhKB2LH/5U2dt+5JXmvlGXNzVF8=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.0.0 h1:BwIoZQbBsTo3v2F5lz5Oy3TlTq4wLKTLV260EVTEWco=
github.com/valyala/fasthttp v1.0.0/go.mod h1:4vX61m6KN+xDduDNwXrhIAVZaZaZiQ1luJk8LWSxF3s=
github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16 h1:y6ce7gCWtnH+m3dCjzQ1PCuwl28DDIc3VNnvY29DlIA=
golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/net v0.0.0-20180911220305-26e67e76b6c3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33 h1:I6FyU15t786LL7oL/hn43zqTuEGr4PN7F4XJ1p4E3Y8=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=

View file

@ -0,0 +1,31 @@
subject=/C=US/ST=Washington/L=Redmond/O=Nintendo of America, Inc./OU=IS/CN=CTR Common Prod 1/emailAddress=ca@noa.nintendo.com
issuer=/C=US/ST=Washington/O=Nintendo of America Inc./OU=IS/CN=Nintendo CA - G3
-----BEGIN CERTIFICATE-----
MIIEwzCCA6ug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kvfXzsj+V5UkZchew2pOqhrqpPknGIlFCeTDYjN8jqJyX4EljJ
1FTegfhfSe+XR7KOIh8b+d+fgftyRIp3M//BUF1FtwL789f/VakaIkz6Ret/+8tA
3UHqKKGtgSRL9kiTMVYy64pBG9A=
-----END PRIVATE KEY-----

View file

@ -1,5 +1,5 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
@ -7,17 +7,15 @@
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
@ -72,7 +60,7 @@ modification follow.
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found.
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -1,17 +0,0 @@
#!/bin/bash
oldsum="$(md5sum output.log)"
clear
echo "Yamamura chat log:"
echo "----------------------------"
tail -n 20 output.log
while [[ True ]]; do
newsum="$(md5sum output.log)"
if [[ "$oldsum" != "$newsum" ]]; then
clear
echo "Yamamura chat log:"
echo "----------------------------"
tail -n 20 output.log
oldsum="$newsum"
fi
sleep 2
done

2
readme.md Normal file
View file

@ -0,0 +1,2 @@
# yamamura
the official bot of the pretendo discord server

View file

@ -1,24 +0,0 @@
#!/usr/local/bin/python3.6
from discord.ext.commands import Bot
import discord
import json
with open("config.json", "r") as cfg:
cfg = json.load(cfg)
bot = Bot(description="Yamamura", command_prefix=cfg["prefix"])
@bot.event
async def on_ready():
for x in bot.guilds:
server = x
break
while True:
msg = input("message: ")
channel_name = input("channel: ")
channel = discord.utils.get(server.channels, name=channel_name)
await channel.send(msg)
print("sent")
bot.run(cfg["token"])

395
yamamura.go Normal file
View file

@ -0,0 +1,395 @@
/*
yamamura - that one discord bot used in the pretendo discord server
Copyright (C) 2018 superwhiskers <whiskerdev@protonmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/signal"
"regexp"
"runtime"
"strings"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
"github.com/superwhiskers/harmony"
"github.com/superwhiskers/fennel"
)
type configType struct {
Token string `json:"token"`
Prefix string `json:"prefix"`
Moderators []string `json:"moderators"`
SpamChannels []string `json:"spam_channels"`
VotingChannels []string `json:"voting_channels"`
}
var (
config configType
handler *harmony.CommandHandler
mentionRegex *regexp.Regexp
ayyRegex *regexp.Regexp
nintyClient *fennel.AccountServerClient
)
func init() {
log.SetOutput(os.Stdout)
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
})
}
func main() {
runtime.GOMAXPROCS(100)
logfile, err := os.OpenFile("yamamura.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Warnf("unable to open logfile. falling back to stdout only. error: %v", err)
} else {
defer logfile.Close()
log.SetOutput(io.MultiWriter(os.Stdout, logfile))
}
configByte, err := ioutil.ReadFile("config.json")
if err != nil {
log.Panicf("unable to read config file. error: %v", err)
}
err = json.Unmarshal(configByte, &config)
if err != nil {
log.Panicf("unable to parse config file. error: %v", err)
}
var clientInfo = fennel.ClientInformation{
ClientID: "ea25c66c26b403376b4c5ed94ab9cdea",
ClientSecret: "d137be62cb6a2b831cad8c013b92fb55",
DeviceCert: "",
Environment: "",
Country: "US",
Region: "2",
SysVersion: "1111",
Serial: "1",
DeviceID: "1",
DeviceType: "",
PlatformID: "1",
}
nintyClient, err = fennel.NewAccountServerClient("https://account.pretendo.cc/v1/api", "keypair/ctr-common-cert.pem", "keypair/ctr-common-key.pem", clientInfo)
if err != nil {
log.Panicf("unable to create fennel nintendo client. error: %v", err)
}
dg, err := discordgo.New(fmt.Sprintf("Bot %s", config.Token))
if err != nil {
log.Panicf("unable to create a discordgo session object. error: %v", err)
}
mentionRegex = regexp.MustCompile("(?i)\\@everyone|(?i)\\@here")
ayyRegex = regexp.MustCompile("(?i)\\bay{1,}\\b")
handler = harmony.New(config.Prefix, true)
handler.OnMessageHandler = onMessage
handler.AddCommand("help", false, help)
handler.AddCommand("status", false, status)
//handler.AddCommand("role", false, roleMeta)
dg.AddHandler(handler.OnMessage)
dg.AddHandler(onReady)
err = dg.Open()
if err != nil {
log.Panicf("unable to open the discord session. error: %v", err)
}
log.Printf("press ctrl-c to stop the bot...")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
dg.Close()
}
// handles message create events
func onMessage(s *discordgo.Session, m *discordgo.MessageCreate) {
if strings.HasPrefix(m.Content, config.Prefix) {
return
}
if m.Author.Bot == true {
return
}
member, err := s.GuildMember(m.GuildID, m.Author.ID)
if err != nil {
log.Errorf("unable to get guild member. error: %v", err)
return
}
content, err := m.ContentWithMoreMentionsReplaced(s)
if err != nil {
content = m.ContentWithMentionsReplaced()
}
content = mentionRegex.ReplaceAllStringFunc(content, func(in string) string {
return strings.Join([]string{"<at>", in[1:]}, "")
})
if strings.ToLower(content) == "i'm a teapot" {
for _, roleID := range member.Roles {
if roleID == "415067373691863040" {
err = s.GuildMemberRoleRemove(m.GuildID, m.Author.ID, "415067373691863040")
if err != nil {
log.Errorf("unable to remove role. error: %v", err)
_, err = s.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{
Title: "error",
Description: "sorry, but i was unable to remove your role",
Color: 0xFFF176,
Footer: &discordgo.MessageEmbedFooter{
Text: "built with ❤ by superwhiskers#3210",
},
})
if err != nil {
log.Errorf("unable to send message. error: %v", err)
}
return
}
_, err = s.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{
Title: "removed role",
Description: "you no longer have the real devs role",
Color: 0xFFF176,
Footer: &discordgo.MessageEmbedFooter{
Text: "built with ❤ by superwhiskers#3210",
},
})
if err != nil {
log.Errorf("unable to send message. error: %v", err)
}
return
}
}
err = s.GuildMemberRoleAdd(m.GuildID, m.Author.ID, "415067373691863040")
if err != nil {
log.Errorf("unable to add role. error: %v", err)
_, err = s.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{
Title: "error",
Description: "sorry, but i was unable to add your role",
Color: 0xFFF176,
Footer: &discordgo.MessageEmbedFooter{
Text: "built with ❤ by superwhiskers#3210",
},
})
if err != nil {
log.Errorf("unable to send message. error: %v", err)
}
return
}
return
}
if ayyRegex.MatchString(content) {
lmao := ayyRegex.ReplaceAllStringFunc(content, func(in string) string {
lmao := strings.Replace(in[1:], "y", "o", -1)
lmao = strings.Replace(lmao, "Y", "O", -1)
if in[0] == []byte("a")[0] {
lmao = strings.Join([]string{"lma", lmao}, "")
} else {
lmao = strings.Join([]string{"LMA", lmao}, "")
}
return lmao
})
if len(lmao) > 2000 {
_, err := s.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{
Title: "error",
Description: "sorry, but the resulting message was too long",
Color: 0xFFF176,
Footer: &discordgo.MessageEmbedFooter{
Text: "built with ❤ by superwhiskers#3210",
},
})
if err != nil {
log.Errorf("unable to send message. error: %v", err)
}
return
}
_, err = s.ChannelMessageSend(m.ChannelID, lmao)
if err != nil {
log.Errorf("unable to send message. error: %v", err)
}
return
}
}
// handles the ready event
func onReady(s *discordgo.Session, r *discordgo.Ready) {
time.Sleep(500 * time.Millisecond)
log.Printf("logged in as %s on %d servers...", r.User.String(), len(r.Guilds))
}
// command that shows the help message
func help(s *discordgo.Session, m *discordgo.MessageCreate, args []string) {
_, err := s.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{
Title: "yamamura",
Description: "the official pretendo discord bot",
Color: 0xFFF176,
Fields: []*discordgo.MessageEmbedField{
{
Name: "commands",
Value: `**help**: shows this message
**status**: checks the status of the pretendo servers
**role [toggle <name>|list]**: toggle a role or list the available roles to toggle`,
Inline: false,
},
},
Footer: &discordgo.MessageEmbedFooter{
Text: "built with ❤ by superwhiskers#3210",
},
})
if err != nil {
log.Errorf("unable to send message. error: %v", err)
}
return
}
// server status command
func status(s *discordgo.Session, m *discordgo.MessageCreate, args []string) {
_, _, err := nintyClient.GetEULA("US", "@latest")
if err != nil {
// probably offline
_, err := s.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{
Title: "server status",
Description: "○ account.pretendo.cc",
Color: 0xFFF176,
Footer: &discordgo.MessageEmbedFooter{
Text: "built with ❤ by superwhiskers#3210",
},
})
if err != nil {
log.Errorf("unable to send message. error: %v", err)
}
return
}
_, err = s.ChannelMessageSendEmbed(m.ChannelID, &discordgo.MessageEmbed{
Title: "server status",
Description: "● account.pretendo.cc",
Color: 0xFFF176,
Footer: &discordgo.MessageEmbedFooter{
Text: "built with ❤ by superwhiskers#3210",
},
})
if err != nil {
log.Errorf("unable to send message. error: %v", err)
}
}