Implemented logging, expanded economy

Mod commands are now logged into data/mod/mod.log
Economy events are logged into data/economy/economy.log
Added !bank set to set credits (admin/owner)
Added !bank transfer to transfer credits between bank accounts
Modified !bank balance, it can now show the balance of other users too
This commit is contained in:
Twentysix 2016-02-20 22:10:30 +01:00
parent b753a26a77
commit cff8b8cd1c
3 changed files with 116 additions and 33 deletions

View File

@ -7,6 +7,7 @@ from copy import deepcopy
from __main__ import send_cmd_help from __main__ import send_cmd_help
import os import os
import time import time
import logging
slot_payouts = """Slot machine payouts: slot_payouts = """Slot machine payouts:
:two: :two: :six: Bet * 5000 :two: :two: :six: Bet * 5000
@ -42,18 +43,59 @@ class Economy:
if user.id not in self.bank: if user.id not in self.bank:
self.bank[user.id] = {"name" : user.name, "balance" : 100} self.bank[user.id] = {"name" : user.name, "balance" : 100}
fileIO("data/economy/bank.json", "save", self.bank) fileIO("data/economy/bank.json", "save", self.bank)
await self.bot.say("{} `Account opened. Current balance: {}`".format(user.mention, str(self.check_balance(user.id)))) await self.bot.say("{} Account opened. Current balance: {}".format(user.mention, str(self.check_balance(user.id))))
else: else:
await self.bot.say("{} `You already have an account at the Twentysix bank.`".format(user.mention)) await self.bot.say("{} You already have an account at the Twentysix bank.".format(user.mention))
@_bank.command(pass_context=True) @_bank.command(pass_context=True)
async def balance(self, ctx): async def balance(self, ctx, user : discord.Member=None):
"""Shows your current balance""" """Shows balance of user.
user = ctx.message.author
if self.account_check(user.id): Defaults to yours."""
await self.bot.say("{} `Your balance is: {}`".format(user.mention, str(self.check_balance(user.id)))) if not user:
user = ctx.message.author
if self.account_check(user.id):
await self.bot.say("{} Your balance is: {}".format(user.mention, str(self.check_balance(user.id))))
else:
await self.bot.say("{} You don't have an account at the Twentysix bank. Type !register to open one.".format(user.mention, str(self.check_balance(user.id))))
else: else:
await self.bot.say("{} `You don't have an account at the Twentysix bank. Type !register to open one.`".format(user.mention, str(self.check_balance(user.id)))) if self.account_check(user.id):
balance = self.check_balance(user.id)
await self.bot.say("{}'s balance is {}".format(user.name, str(balance)))
else:
await self.bot.say("That user has no bank account.")
@_bank.command(pass_context=True)
async def transfer(self, ctx, user : discord.Member, sum : int):
"""Transfer credits to other users"""
author = ctx.message.author
if author == user:
await self.bot.say("You can't transfer money to yourself.")
return
if self.account_check(user.id):
if self.enough_money(author.id, sum):
self.withdraw_money(author.id, sum)
self.add_money(user.id, sum)
logger.info("{}({}) transferred {} credits to {}({})".format(author.name, author.id, str(sum), user.name, user.id))
await self.bot.say("{} credits have been transferred to {}'s account.".format(str(sum), user.name))
else:
await self.bot.say("You don't have that sum in your bank account.")
else:
await self.bot.say("That user has no bank account.")
@_bank.command(name="set", pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def _set(self, ctx, user : discord.Member, sum : int):
"""Sets money of user's bank account
Admin/owner restricted."""
author = ctx.message.author
done = self.set_money(user.id, sum)
if done:
logger.info("{}({}) set {} credits to {} ({})".format(author.name, author.id, str(sum), user.name, user.id))
await self.bot.say("{}'s credits have been set to {}".format(user.name, str(sum)))
else:
await self.bot.say("User has no bank account.")
@commands.command(pass_context=True, no_pm=True) @commands.command(pass_context=True, no_pm=True)
async def payday(self, ctx): async def payday(self, ctx):
@ -65,15 +107,15 @@ class Economy:
if abs(self.payday_register[id] - int(time.perf_counter())) >= self.settings["PAYDAY_TIME"]: if abs(self.payday_register[id] - int(time.perf_counter())) >= self.settings["PAYDAY_TIME"]:
self.add_money(id, self.settings["PAYDAY_CREDITS"]) self.add_money(id, self.settings["PAYDAY_CREDITS"])
self.payday_register[id] = int(time.perf_counter()) self.payday_register[id] = int(time.perf_counter())
await self.bot.say("{} `Here, take some credits. Enjoy! (+{} credits!)`".format(author.mention, str(self.settings["PAYDAY_CREDITS"]))) await self.bot.say("{} Here, take some credits. Enjoy! (+{} credits!)".format(author.mention, str(self.settings["PAYDAY_CREDITS"])))
else: else:
await self.bot.say("{} `Too soon. You have to wait {} seconds between each payday.`".format(author.mention, str(self.settings["PAYDAY_TIME"]))) await self.bot.say("{} Too soon. You have to wait {} seconds between each payday.".format(author.mention, str(self.settings["PAYDAY_TIME"])))
else: else:
self.payday_register[id] = int(time.perf_counter()) self.payday_register[id] = int(time.perf_counter())
self.add_money(id, self.settings["PAYDAY_CREDITS"]) self.add_money(id, self.settings["PAYDAY_CREDITS"])
await self.bot.say("{} `Here, take some credits. Enjoy! (+{} credits!)`".format(author.mention, str(self.settings["PAYDAY_CREDITS"]))) await self.bot.say("{} Here, take some credits. Enjoy! (+{} credits!)".format(author.mention, str(self.settings["PAYDAY_CREDITS"])))
else: else:
await self.bot.say("{} `You need an account to receive credits.`".format(author.mention)) await self.bot.say("{} You need an account to receive credits.".format(author.mention))
@commands.command(pass_context=True) @commands.command(pass_context=True)
async def payouts(self, ctx): async def payouts(self, ctx):
@ -88,9 +130,9 @@ class Economy:
if bid >= self.settings["SLOT_MIN"] and bid <= self.settings["SLOT_MAX"]: if bid >= self.settings["SLOT_MIN"] and bid <= self.settings["SLOT_MAX"]:
await self.slot_machine(ctx.message, bid) await self.slot_machine(ctx.message, bid)
else: else:
await self.bot.say("{0} `Bid must be between {1} and {2}.`".format(author.mention, self.settings["SLOT_MIN"], self.settings["SLOT_MAX"])) await self.bot.say("{0} Bid must be between {1} and {2}.".format(author.mention, self.settings["SLOT_MIN"], self.settings["SLOT_MAX"]))
else: else:
await self.bot.say("{0} `You need an account with enough funds to play the slot machine.`".format(author.mention)) await self.bot.say("{0} You need an account with enough funds to play the slot machine.".format(author.mention))
async def slot_machine(self, message, bid): async def slot_machine(self, message, bid):
reel_pattern = [":cherries:", ":cookie:", ":two:", ":four_leaf_clover:", ":cyclone:", ":sunflower:", ":six:", ":mushroom:", ":heart:", ":snowflake:"] reel_pattern = [":cherries:", ":cookie:", ":two:", ":four_leaf_clover:", ":cyclone:", ":sunflower:", ":six:", ":mushroom:", ":heart:", ":snowflake:"]
@ -109,42 +151,42 @@ class Economy:
if line[0] == ":two:" and line[1] == ":two:" and line[2] == ":six:": if line[0] == ":two:" and line[1] == ":two:" and line[2] == ":six:":
bid = bid * 5000 bid = bid * 5000
await self.bot.send_message(message.channel, "{}{} `226! Your bet is multiplied * 5000! {}!` ".format(display_reels, message.author.mention, str(bid))) await self.bot.send_message(message.channel, "{}{} 226! Your bet is multiplied * 5000! {}! ".format(display_reels, message.author.mention, str(bid)))
elif line[0] == ":four_leaf_clover:" and line[1] == ":four_leaf_clover:" and line[2] == ":four_leaf_clover:": elif line[0] == ":four_leaf_clover:" and line[1] == ":four_leaf_clover:" and line[2] == ":four_leaf_clover:":
bid += 1000 bid += 1000
await self.bot.send_message(message.channel, "{}{} `Three FLC! +1000!` ".format(display_reels, message.author.mention)) await self.bot.send_message(message.channel, "{}{} Three FLC! +1000! ".format(display_reels, message.author.mention))
elif line[0] == ":cherries:" and line[1] == ":cherries:" and line[2] == ":cherries:": elif line[0] == ":cherries:" and line[1] == ":cherries:" and line[2] == ":cherries:":
bid += 800 bid += 800
await self.bot.send_message(message.channel, "{}{} `Three cherries! +800!` ".format(display_reels, message.author.mention)) await self.bot.send_message(message.channel, "{}{} Three cherries! +800! ".format(display_reels, message.author.mention))
elif line[0] == line[1] == line[2]: elif line[0] == line[1] == line[2]:
bid += 500 bid += 500
await self.bot.send_message(message.channel, "{}{} `Three symbols! +500!` ".format(display_reels, message.author.mention)) await self.bot.send_message(message.channel, "{}{} Three symbols! +500! ".format(display_reels, message.author.mention))
elif line[0] == ":two:" and line[1] == ":six:" or line[1] == ":two:" and line[2] == ":six:": elif line[0] == ":two:" and line[1] == ":six:" or line[1] == ":two:" and line[2] == ":six:":
bid = bid * 4 bid = bid * 4
await self.bot.send_message(message.channel, "{}{} `26! Your bet is multiplied * 4! {}!` ".format(display_reels, message.author.mention, str(bid))) await self.bot.send_message(message.channel, "{}{} 26! Your bet is multiplied * 4! {}! ".format(display_reels, message.author.mention, str(bid)))
elif line[0] == ":cherries:" and line[1] == ":cherries:" or line[1] == ":cherries:" and line[2] == ":cherries:": elif line[0] == ":cherries:" and line[1] == ":cherries:" or line[1] == ":cherries:" and line[2] == ":cherries:":
bid = bid * 3 bid = bid * 3
await self.bot.send_message(message.channel, "{}{} `Two cherries! Your bet is multiplied * 3! {}!` ".format(display_reels, message.author.mention, str(bid))) await self.bot.send_message(message.channel, "{}{} Two cherries! Your bet is multiplied * 3! {}! ".format(display_reels, message.author.mention, str(bid)))
elif line[0] == line[1] or line[1] == line[2]: elif line[0] == line[1] or line[1] == line[2]:
bid = bid * 2 bid = bid * 2
await self.bot.send_message(message.channel, "{}{} `Two symbols! Your bet is multiplied * 2! {}!` ".format(display_reels, message.author.mention, str(bid))) await self.bot.send_message(message.channel, "{}{} Two symbols! Your bet is multiplied * 2! {}! ".format(display_reels, message.author.mention, str(bid)))
else: else:
await self.bot.send_message(message.channel, "{}{} `Nothing! Lost bet.` ".format(display_reels, message.author.mention)) await self.bot.send_message(message.channel, "{}{} Nothing! Lost bet. ".format(display_reels, message.author.mention))
self.withdraw_money(message.author.id, bid) self.withdraw_money(message.author.id, bid)
await self.bot.send_message(message.channel, "`Credits left: {}`".format(str(self.check_balance(message.author.id)))) await self.bot.send_message(message.channel, "Credits left: {}".format(str(self.check_balance(message.author.id))))
return True return True
self.add_money(message.author.id, bid) self.add_money(message.author.id, bid)
await self.bot.send_message(message.channel, "`Current credits: {}`".format(str(self.check_balance(message.author.id)))) await self.bot.send_message(message.channel, "Current credits: {}".format(str(self.check_balance(message.author.id))))
@commands.group(pass_context=True, no_pm=True) @commands.group(pass_context=True, no_pm=True)
@checks.mod_or_permissions() @checks.admin_or_permissions(manage_server=True)
async def economyset(self, ctx): async def economyset(self, ctx):
"""Changes economy module settings""" """Changes economy module settings"""
if ctx.invoked_subcommand is None: if ctx.invoked_subcommand is None:
msg = "```" msg = ""
for k, v in self.settings.items(): for k, v in self.settings.items():
msg += str(k) + ": " + str(v) + "\n" msg += str(k) + ": " + str(v) + "\n"
msg += "\nType help economyset to see the list of commands.```" msg += "\nType help economyset to see the list of commands."
await self.bot.say(msg) await self.bot.say(msg)
@economyset.command() @economyset.command()
@ -213,6 +255,14 @@ class Economy:
else: else:
return False return False
def set_money(self, id, amount):
if self.account_check(id):
self.bank[id]["balance"] = amount
fileIO("data/economy/bank.json", "save", self.bank)
return True
else:
return False
def check_folders(): def check_folders():
if not os.path.exists("data/economy"): if not os.path.exists("data/economy"):
print("Creating data/economy folder...") print("Creating data/economy folder...")
@ -232,6 +282,12 @@ def check_files():
fileIO(f, "save", {}) fileIO(f, "save", {})
def setup(bot): def setup(bot):
global logger
check_folders() check_folders()
check_files() check_files()
logger = logging.getLogger("economy")
logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename='data/economy/economy.log', encoding='utf-8', mode='a')
handler.setFormatter(logging.Formatter('%(asctime)s %(message)s', datefmt="[%d/%m/%Y %H:%M]"))
logger.addHandler(handler)
bot.add_cog(Economy(bot)) bot.add_cog(Economy(bot))

View File

@ -4,6 +4,7 @@ from .utils import checks
from .utils.dataIO import fileIO from .utils.dataIO import fileIO
from __main__ import send_cmd_help from __main__ import send_cmd_help
import os import os
import logging
class Mod: class Mod:
"""Moderation tools.""" """Moderation tools."""
@ -15,29 +16,33 @@ class Mod:
self.ignore_list = fileIO("data/mod/ignorelist.json", "load") self.ignore_list = fileIO("data/mod/ignorelist.json", "load")
self.filter = fileIO("data/mod/filter.json", "load") self.filter = fileIO("data/mod/filter.json", "load")
@commands.command(no_pm=True) @commands.command(no_pm=True, pass_context=True)
@checks.admin_or_permissions(kick_members=True) @checks.admin_or_permissions(kick_members=True)
async def kick(self, user : discord.Member): async def kick(self, ctx, user : discord.Member):
"""Kicks user.""" """Kicks user."""
author = ctx.message.author
try: try:
await self.bot.kick(user) await self.bot.kick(user)
logger.info("{}({}) kicked {}({})".format(author.name, author.id, user.name, user.id))
await self.bot.say("Done. That felt good.") await self.bot.say("Done. That felt good.")
except discord.errors.Forbidden: except discord.errors.Forbidden:
await self.bot.say("I'm not allowed to do that.") await self.bot.say("I'm not allowed to do that.")
except Exception as e: except Exception as e:
print(e) print(e)
@commands.command(no_pm=True) @commands.command(no_pm=True, pass_context=True)
@checks.admin_or_permissions(ban_members=True) @checks.admin_or_permissions(ban_members=True)
async def ban(self, user : discord.Member, purge_msg : int=0): async def ban(self, ctx, user : discord.Member, purge_msg : int=0):
"""Bans user and deletes last X days worth of messages. """Bans user and deletes last X days worth of messages.
Minimum 0 days, maximum 7. Defaults to 0.""" Minimum 0 days, maximum 7. Defaults to 0."""
author = ctx.message.author
if purge_msg < 0 or purge_msg > 7: if purge_msg < 0 or purge_msg > 7:
await self.bot.say("Invalid days. Must be between 0 and 7.") await self.bot.say("Invalid days. Must be between 0 and 7.")
return return
try: try:
await self.bot.ban(user, days) await self.bot.ban(user, days)
logger.info("{}({}) banned {}({}), deleting {} days worth of messages".format(author.name, author.id, user.name, user.id, str(purge_msg)))
await self.bot.say("Done. It was about time.") await self.bot.say("Done. It was about time.")
except discord.errors.Forbidden: except discord.errors.Forbidden:
await self.bot.say("I'm not allowed to do that.") await self.bot.say("I'm not allowed to do that.")
@ -63,8 +68,10 @@ class Mod:
cleanup text \"test\" 5 cleanup text \"test\" 5
Remember to use double quotes.""" Remember to use double quotes."""
author = ctx.message.author
message = ctx.message message = ctx.message
cmdmsg = message cmdmsg = message
logger.info("{}({}) deleted {} messages containing '{}' in channel {}".format(author.name, author.id, str(number), text, message.channel.name))
if number > 0 and number < 10000: if number > 0 and number < 10000:
while True: while True:
new = False new = False
@ -82,14 +89,16 @@ class Mod:
break break
@cleanup.command(pass_context=True, no_pm=True) @cleanup.command(pass_context=True, no_pm=True)
async def user(self, ctx, name : discord.Member, number : int): async def user(self, ctx, user : discord.Member, number : int):
"""Deletes last X messages from specified user. """Deletes last X messages from specified user.
Examples: Examples:
cleanup user @\u200bTwentysix 2 cleanup user @\u200bTwentysix 2
cleanup user Red 6""" cleanup user Red 6"""
author = ctx.message.author
message = ctx.message message = ctx.message
cmdmsg = message cmdmsg = message
logger.info("{}({}) deleted {} messages made by {}({}) in channel {}".format(author.name, author.id, str(number), user.name, user.id, message.channel.name))
if number > 0 and number < 10000: if number > 0 and number < 10000:
while True: while True:
new = False new = False
@ -97,7 +106,7 @@ class Mod:
if number == 0: if number == 0:
await self.bot.delete_message(cmdmsg) await self.bot.delete_message(cmdmsg)
return return
if x.author.id == name.id: if x.author.id == user.id:
await self.bot.delete_message(x) await self.bot.delete_message(x)
number -= 1 number -= 1
new = True new = True
@ -112,7 +121,9 @@ class Mod:
Example: Example:
cleanup messages 26""" cleanup messages 26"""
author = ctx.message.author
channel = ctx.message.channel channel = ctx.message.channel
logger.info("{}({}) deleted {} messages in channel {}".format(author.name, author.id, str(number), channel.name))
if number > 0 and number < 10000: if number > 0 and number < 10000:
async for x in self.bot.logs_from(channel, limit=number+1): async for x in self.bot.logs_from(channel, limit=number+1):
await self.bot.delete_message(x) await self.bot.delete_message(x)
@ -391,8 +402,14 @@ def check_files():
fileIO("data/mod/filter.json", "save", {}) fileIO("data/mod/filter.json", "save", {})
def setup(bot): def setup(bot):
global logger
check_folders() check_folders()
check_files() check_files()
logger = logging.getLogger("mod")
logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename='data/mod/mod.log', encoding='utf-8', mode='a')
handler.setFormatter(logging.Formatter('%(asctime)s %(message)s', datefmt="[%d/%m/%Y %H:%M]"))
logger.addHandler(handler)
n = Mod(bot) n = Mod(bot)
bot.add_listener(n.check_filter, "on_message") bot.add_listener(n.check_filter, "on_message")
bot.add_cog(n) bot.add_cog(n)

10
red.py
View File

@ -10,6 +10,7 @@ import glob
import os import os
import time import time
import sys import sys
import logging
# #
# Red, a Discord bot by Twentysix, based on discord.py and its command extension # Red, a Discord bot by Twentysix, based on discord.py and its command extension
@ -368,6 +369,14 @@ def check_configs():
with open(cogs_s_path, "w") as f: with open(cogs_s_path, "w") as f:
f.write(json.dumps(cogs)) f.write(json.dumps(cogs))
def set_logger():
global logger
logger = logging.getLogger("discord")
logger.setLevel(logging.WARNING)
handler = logging.FileHandler(filename='data/red/discord.log', encoding='utf-8', mode='a')
handler.setFormatter(logging.Formatter('%(asctime)s %(message)s', datefmt="[%d/%m/%Y %H:%M]"))
logger.addHandler(handler)
def get_answer(): def get_answer():
choices = ("yes", "y", "no", "n") choices = ("yes", "y", "no", "n")
c = "" c = ""
@ -438,6 +447,7 @@ def main():
global settings global settings
check_folders() check_folders()
check_configs() check_configs()
set_logger()
settings = load_settings() settings = load_settings()
checks.owner = settings["OWNER"] checks.owner = settings["OWNER"]
load_cogs() load_cogs()