`Hi Guys,
I need some help.
So.. ive been developing a discord bot over the last year and trying to make some improvements to the games i have made.. it is basically an economy system that allows users to transfer funds to one another, place bets, and recieve winnings etc.
I have created a slots game that automatically generates winnings and economy but my idea is to modify an exisiting heads or tails game with the same functions to basically:
Allow a user to deposit a bet into an account that holds the winnings/profits/bets etc.
The user will then either select heads or tails to win the challenge.
The winnings will then be transferred directly from the specific account.
My current code is:
mport discord
import random
from discord.ext import commands
from discord.ext import commands, tasks
from discord.ui import select, View
from discord.embeds import Embed
from discord import colour
import asyncio
from itertools import cycle
import os
import json
import datetime
from random import choice
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='!', intents=intents) #Command prefix
#Notifies vs code that the bot is running on VS code#
#client.event
async def on_ready():
print("Bot is ready")
#Slot machine command when user enters !slots 50#
#client.command(pass_context=True)
async def slots(ctx, amount=None):
if amount == None:
em = discord.Embed(title=f'❓Please enter an amount❓',color = discord.Color.red())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount > bal[0]:
em = discord.Embed(title=f'❌You do not have sufficient balance❌')
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
if amount < 0:
em = discord.Embed(title=f'❗Amount must be positive❗')
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
slots = ['🧝♂️', '🔥']
slot1 = slots[random.randint(0, 1)]
slotOutput = '| :{}: |\n'.format(slot1)
ok = discord.Embed(title = "RTC slot machine", color = discord.Color(0xFFEC))
ok.add_field(name = "{}\nWon".format(slotOutput), value = f'You won {1.9*amount} coins')
won = discord.Embed(title = "Slots Machine", color = discord.Color(0xFFEC))
won.add_field(name = "{}\nWon".format(slotOutput), value = f'You won {1.9*amount} coins')
if slot1:
await update_bank(ctx.author, 1.9 * amount)
await ctx.send(embed = won)
return
The deposit bet command for the agreed bet when user enters !db #hostname 500 for example#
#client.command()
async def db(ctx,member : discord.Member,amount = None):
await open_account(ctx.author)
await open_account(member)
if amount == None:
em = discord.Embed(title=f'❓Please enter an amount you wish to bet❓',color = discord.Color.red())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
bal = await update_bank(ctx.author)
if amount == 'all':
amount = bal[0]
amount = int(amount)
if amount > bal[0]:
em = discord.Embed(title=f'❌You do not have sufficient balance❌',color = discord.Color.red())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
if amount < 0:
em = discord.Embed(title =f'❗Amount must be positive❗',color = discord.Color.red())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
await update_bank(ctx.author,-1*amount,'wallet')
await update_bank(member,amount,'bank')
em = discord.Embed(title=f'⚔{ctx.author.name} sent {amount}M RS3 to {member}', description=f'Please select the game/challenge !coinflip !elements or !yesandno⚔',color = discord.Color.green())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
#Creates account details for member of the channel#
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open('bank.json','w') as f:
json.dump(users,f)
return True
#Stores the user wallet amount in the bank.json file#
async def get_bank_data():
with open('bank.json','r') as f:
users = json.load(f)
return users
#Updates the users bank details held within the json file.
async def update_bank(user,change=0,mode = 'wallet'):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open('bank.json','w') as f:
json.dump(users,f)
bal = users[str(user.id)]['wallet'],users[str(user.id)]['bank']
return bal
client.run("'''''")
Im looking for a way to modify the code so it takes the winnings from a specific account by implimenting the account ID or username.
Any ideas?`
Related
So I am having a problem. I am making a game where it eliminates you every 5 seconds by taking away your role. When it eliminates you it will DM you. But I am having trouble as some people have DMs off and when the bot tries to DM them it stops the whole process even with the except Exception block, I have tried everything. Is there anything I did wrong here?
from discord.ext import commands
import discord
import time
import datetime
import random
from setup import ROLEID
import asyncio
class Game(commands.Cog):
def __init__(self, client):
self.client = client
async def guessthenumber(self, ctx, channel):
embed = discord.Embed(title='Minigame!',description='Play this game to win immunity!\nI am thinking of a number, 1-20, first to guess it wins immunity for a round!')
await channel.send(embed=embed)
randnum = random.randint(1,20)
openstatus = 'yes'
await channel.send(randnum)
while openstatus == 'yes':
def check(m):
return ctx.author == m.author
msg = await self.client.wait_for('message', timeout=60.0, check=check)
if msg.content == str(randnum) and openstatus == 'yes':
embed=discord.Embed(title="Number has been guessed!",description=f'{msg.author.mention} has guessed the number!')
await channel.send(embed=embed)
openstatus = 'no'
immunes = []
immunes.append(msg.author)
async def choosekick(self, ctx, channel,list_of_players, role):
the_choices = []
listy = list_of_players
choice1 = random.choice(listy)
listy.remove(choice1)
choice2 = random.choice(listy)
the_choices.append(choice1)
the_choices.append(choice2)
embed = discord.Embed(title='Vote Save!',description = f'Choose one of the following people to save!\n{the_choices[0].mention} or {the_choices[1].mention}')
msg = await channel.send(embed=embed)
await msg.add_reaction('1️⃣')
await msg.add_reaction('2️⃣')
global t1
t1 = 0
global t2
t2 = 0
await asyncio.sleep(10)
async def on_raw_reaction_add(self,payload):
guild = discord.utils.find(lambda g: g.id==payload.guild_id,self.client.guilds)
if payload.emoji.name == '1️⃣':
t1 += 1
if payload.emoji.name == '2️⃣':
t2 +=1
if t1 > t2:
loser = t1
await channel.send(f"{the_choices[1].mention} has been voted out!")
list_of_players.remove[the_choices[1]]
await the_choices[1].remove_roles(role)
await the_choices[1].send('You have been eliminated from the game')
else:
loser = t2
await channel.send(f"{the_choices[0].mention} has been voted out!")
await the_choices[0].remove_roles(role)
await the_choices[0].send('You have been eliminated from the game!')
list_of_players.remove(the_choices[0])
#commands.command()
async def commence(self, ctx):
try:
guild = ctx.guild
role = guild.get_role(ROLEID)
channel = await guild. create_text_channel('Elimination Game')
await channel.set_permissions(ctx.guild.default_role, send_messages=False,view_channel=False)
await channel.set_permissions(role, send_messages=True,view_channel=True)
embed = discord.Embed(title = 'The game has been commenced!', description=f'{role.mention} The elimination process will start in two minutes. This game works as follows.\nA person is eliminated every 3 minutes however there will be minigames to gain immunity! Keep your eye out for them!')
list_of_players = []
await channel.send(embed=embed)
for member in guild.members:
if role in member.roles:
list_of_players.append(member)
list_of_players.remove(self.client.user)
if len(list_of_players) < 45:
skipterval = 1
else:
skipterval = len(list_of_players) // 45
divided_point = len(list_of_players)//4
og_list = len(list_of_players)-divided_point
while len(list_of_players) >og_list:
await asyncio.sleep(5)
print(skipterval)
for loser in range(0,skipterval):
print('ii')
holder = random.choice(list_of_players)
eliminated_player = holder
list_of_players.remove(eliminated_player)
await eliminated_player.remove_roles(role)
embed = discord.Embed(title = 'Elimination!',description=f'{eliminated_player.mention} has been eliminated out of the game!')
await channel.send(embed=embed)
await eliminated_player.send('You have been eliminated from the game!')
print('dones')
randgame = random.randint(1,2)
if randgame == 1:
await self.guessthenumber(ctx, channel)
nextgame = 2
elif randgame == 2:
await self.choosekick(ctx,channel,list_of_players,role)
nextgame = 1
og_list = len(list_of_players) //4 + len(list_of_players) //4
embed = discord.Embed(title='Game Resumed!',description='The game has been resumed eliminations are starting...')
await channel.send(embed=embed)
if nextgame==1:
self.guessthenumber(ctx,channel)
if nextgame==2:
self.choosekick(ctx,channel,list_of_players,role)
except Exception:
pass
def setup(client):
client.add_cog(Game(client))
Edit: I probably should have added that I did all of the following code on repl.it, though I doubt it makes any difference.
Edit 2: I don't know what I did, but now absolutely nothing works. The 'ready' message won't show in the console. It might have to do with the 'keep_alive' file I added in.
So I was going about my day, trying to figure out what the problem is with this snippet of code, until I realized 'Hey, I could try to ask Stack Overflow'!
For context, whenever I run the bot and type in a command (i.e. '!rank'), the bot doesn't seem to recognize the command. The console is just empty of red words, unless I use a nonexisting command. This is the console after I used three commands: '!rank', '!leaderboard', and '!yeet', which purposefully doesn't exist.
In case you're too lazy to open the image, the console goes:
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "yeet" is not found
Here's the code:
from keep_alive import keep_alive
from discord.ext import commands
import discord
import os
import levelsys
cogs = [levelsys]
client = commands.Bot(command_prefix="!", intents = discord.Intents.all())
token = os.environ.get("DISCORD_BOT_SECRET")
client.run(token)
keep_alive()
token = os.environ.get("DISCORD_BOT_SECRET")
client.run(token)
for i in range(len(cogs)):
cogs[i].setup(client)
import discord
from discord.ext import commands
from pymongo import MongoClient
general = [806613968684318720]
level = ["Sperm Whale", "Artillery General", "Commander", "Supreme General",]
levelnum = [1,5,10,15]
cluster = MongoClient("mongodb+srv://[Username]:[Password]#kingdom-kun.lffd9.mongodb.net/Kingdom-kun?retryWrites=true&w=majority")
client = discord.Client
leveling = cluster["discord"]["levelling"]
class levelsys(commands.Cog):
def _init_(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("Kingdom-kun is ready to come!")
#commands.Cog.listener()
async def on_message(self, message):
if message.channel == general:
stats = leveling.find_one({"id" : message.author.id})
if not message.author.bot:
if stats is None:
newuser = {"id": message.author.id, "xp": 100}
leveling.insert_one(newuser)
else:
xp = stats["xp"] +5
leveling.update_one({"id": message.author.id}, {"$set": {"xp"}})
lvl = 0
while True:
if xp < {(50*(lvl**2))+(50*(lvl-1))}:
break
lvl +=1
xp -= {(50*(lvl-1)**2)+(50*(lvl-1))}
if xp == 0:
await message.channel.send(f"Well done {message.author.mention}! You were promoted to **Level: {lvl}**")
for i in range(len(level)):
if lvl == levelnum[i]:
await message.author.add_roles(discord.utils.get(message.author.guild.roles, name=level[i]))
embed = discord.Embed(description=f"{message.author.mention} you have gotten role **{level[i]}**!!!")
embed.set_thumbnail(url=message.author.avatar_url)
await message.channel.send(embed=embed)
#This is rank command
#commands.command()
async def rank(self, ctx):
if ctx.channel.id == general:
stats = leveling.find_one({"id": ctx.author.id})
if stats is None:
embed = discord.Embed(description = "You haven't sent any messages, no rank!!!")
await ctx.channelsned(embed=embed)
else:
xp = stats["xp"]
lvl = 0
rank = 0
while True:
if xp < {(50*(lvl**2))+(50*(lvl-1))}:
break
lvl += 1
xp -= {(50*(lvl-1)**2)+(50*(lvl-1))}
boxes = [(xp/(200*((1/2) * lvl)))*20]
rankings = leveling.find().sort("xp",-1)
for x in rankings:
rank += 1
if stats("id") == x["id"]:
break
embed = discord.Embed(title="{}'s level stats".format(ctx.author.name))
embed.add_field(name="Name", value = ctx.author.mention, inline=True)
embed.add_field(name="XP", value = f"{(xp/(200*((1/2)* lvl)))*20}", inline=True)
embed.add_field(name="Rank", value = f"{rank}/{ctx.guild.member_count}", inline=True)
embed.add_field(name="Progress Bar[lvl]", value = boxes * ":blue_square:" * (20-boxes) * ":white_large_square:", inline=False)
embed.set_thumbnail(url=ctx.author.avatar_url)
await ctx.channel.send(embed=embed)
#This is leaderboard command
#commands.command()
async def leaderboard(self, ctx):
if (ctx.channel.id == general):
rankings = leveling.find().sort("xp",-1)
i=1
embed = discord.Embed(title = "Rankings:")
for x in rankings:
try:
temp = ctx.guild.get_member(x["id"])
tempxp = x["xp"]
embed.add_field(name=f"(i): {temp.name}", value=f"Total XP: {tempxp}", inline=False)
i == 1
except:
pass
if i == 11:
break
await ctx.channel.send(embed=embed)
def setup(client):
client.add_cog(levelsys(client))
(This is the keep_alive file I added on that somehow screwed everything up)
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/')
def home():
return "OwO mode pog?"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
I've tried a lot of things - changing brackets to parentheses then back again, retyping the entire thing... again, and more, yet nothing changes. If anyone could answer this conundrum, I'd be very thankful.
Anyway, have a nice day!
I have a for loop that runs through a list of questions creating an embed for each question. It is meant to then wait for an answer and then ask the next question. I then upload the answers to a mongodb database (after running some checks to ensure they are valid answers.
The issue I am having is that sometimes (3 in 10 tries) it will ask two questions directly after one another without giving any time to respond to the first. I have played around with sleep() but found it still happens.
Would appreciate any help you can offer!
import re
import datetime
from copy import deepcopy
import emojis
import asyncio
import discord
import math
import random
from discord.ext import commands, tasks
from dateutil.relativedelta import relativedelta
from utils.util import GetMessage
from time import sleep
"""
product = ['Name': 'Example_Name', 'Description': 'Example Description', 'Quantity in stock': 10, 'Price': 400]
Name =product[0]
Description = product[1]
Quantity = product[2]
Price= product[3]
"""
class Shop(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
print(f"{self.__class__.__name__} Cog has been loaded\n-----")
#commands.command(
name='ShopAddProduct',
#aliases=['w'],
description="List all the Shops",
#usage = "[User] <Name>"
)
#commands.has_role("Server Player")
#commands.has_permissions(send_messages=True)
async def ShopAddProduct(self, ctx):
member = ctx.author
channel = await member.create_dm()
await channel.send("Lets add a product. Answer the following questions to add a product to your shop")
questionList = [
["What is your shop called?","Enter the Name of your shop"],
["What is the product called?","Enter what your product is called"],
["Describe your product","Enter a description"],
["How many of them do you have ready to sell?","Enter how many you have in stock"],
["how much are you selling them for?","Enter how many credits you want for this product."]
]
answers = {}
for i, question in enumerate(questionList):
#answer = await GetMessage(self.bot, ctx, question[0], question[1])
embed = discord.Embed(
title=f"{question[0]}",
description =f"{question[1]}",
)
embed.set_thumbnail(url=ctx.guild.icon_url)
sent = await channel.send(embed=embed)
try:
answer = await self.bot.wait_for(
"message",
timeout=60,
check=lambda message: isinstance(message.channel, discord.channel.DMChannel)
)
except asyncio.TimeoutError:
await sent.delete()
await channel.send("Cancelling due to timeout.", delete_after=10)
sleep(2)
answers[i] = answer.content
embed = discord.Embed(name="Add Product")
for key, value in answers.items():
embed.add_field(name=f"Question: `{questionList[key][0]}`", value=f"Answer: `{value}`", inline=False)
m = await channel.send("Are these all valid?", embed=embed)
await m.add_reaction("✅")
await m.add_reaction("🇽")
try:
reaction, member = await self.bot.wait_for(
"reaction_add",
timeout=60,
check=lambda reaction, user: user == ctx.author
and reaction.message.channel == channel
)
except asyncio.TimeoutError:
await channel.send("Confirmation Failure. Please try again.")
return
if str(reaction.emoji) not in ["✅", "🇽"] or str(reaction.emoji) == "🇽":
await channel.send("Cancelling Product Addition!")
#check answers validity
check = await self.bot.shop.find_by_id(answers[0])
if check == None:
await channel.send(f"The shop `{answers[0]}` does not exist! Please try again.")
return
if not answers[3].isdigit():
#not isinstance(answers[3],int):
await channel.send(f"The quantity you submitted (`{answers[3]}`) must be whole number (integer)! Please try again.")
return
if not answers[4].isdigit():
#not isinstance(answers[4],int):
await channel.send(f"The price you submitted (`{answers[4]}`) must be whole number (integer)! Please try again.")
return
shopcheck = await self.bot.shopCatalogue.find_by_id(answers[0])
productlist = shopcheck['Products']
print(productlist)
product = [answers[1], answers[2], int(answers[3]), int(answers[4])]
productlist.append(product)
print(product)
print(productlist)
data = {
'_id': shopcheck['_id'],
'Products': productlist
}
guild=ctx.guild
await self.bot.shopCatalogue.upsert(data)
embed = discord.Embed(
title=f"Product Added to Shop Catalogue!",
#description =,
)
embed.add_field(
name=f"Product:",
value=answers[1],
inline=True
)
embed.add_field(
name=f"Description:",
value=answers[2],
inline=True
)
embed.add_field(
name=f"Quantity:",
value=answers[3],
inline=False
)
embed.add_field(
name=f"Price:",
value=answers[4],
inline=True
)
embed.set_thumbnail(url=ctx.guild.icon_url)
sent = await channel.send(embed=embed)
def setup(bot):
bot.add_cog(Shop(bot))
I've seen this error before, it's happens when the bots message sends fast enough to pass the check, easy fix just make sure that only you can answer to the messages
# add this
def check(message):
channel_id = message.channel.id
author_id = message.author.id
return channel_id == ctx.channel.id and author_id == ctx.author.id
# change this
reaction, member = await self.bot.wait_for(
"reaction_add",
timeout=60,
check=check
)
I have made a Leveling system but i can't figure out to make a cooldown in on_message
i want to add a BucketType.member cooldown and as im using MondoDB for database so i can't afford to store the last time they send message instead im looking for a cooldown for on_message which works similar to commands cooldown so it can automatically take any action
This is the code so far
#commands.Cog.listener()
async def on_message(self , message):
if message.channel.id in talk_channels:
stats = leveling.find_one({"id":message.author.id})
if not message.author.bot:
if stats is None:
new_user = {"id" : message.author.id, "xp" : 0}
leveling.insert_one(new_user)
else:
xp = stats["xp"] + 5
leveling.update_one({"id" : message.author.id}, {"$set" : {"xp" : xp}})
lvl = 0
while True:
if xp < ((50*(lvl**2))+(50*lvl)):
break
lvl += 1
xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
if xp == 0:
await message.channel.send(f"Congo you leveled up {message.author.mention} to **level: {lvl}**")
for i in range(len(level_role)):
if lvl == levelnum[i]:
await message.author.add_roles(discord.utils.get(message.author.guild.roles, name=level_role[i]))
embed = discord.Embed(title="LEVEL UP", description=f"You have reached a mile stone of {lvl} and has got role **{level_role[i]}**", color=0x00ffff)
embed.set_thumbnail(url=message.author.avatar_url)
await message.channel.send(embed=embed)
You should use CooldownMapping.from_cooldown to add cooldowns to the on_message event, example:
import typing
import discord
from discord.ext import commands
class SomeCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._cd = commands.CooldownMapping.from_cooldown(1, 6.0, commands.BucketType.member) # Change accordingly
# rate, per, BucketType
def get_ratelimit(self, message: discord.Message) -> typing.Optional[int]:
"""Returns the ratelimit left"""
bucket = self._cd.get_bucket(message)
return bucket.update_rate_limit()
#commands.Cog.listener()
async def on_message(self, message):
if "check something":
# Getting the ratelimit left
ratelimit = self.get_ratelimit(message)
if ratelimit is None:
# The user is not ratelimited, you can add the XP or level up the user here
else:
# The user is ratelimited
I'm using discord.py to create a multipurpose discord bot, but I have been having some trouble making custom currency.
I decided on using a .json file to store the names and currency of everyone on the server, but I'm getting this error when I run this:
from dotenv import load_dotenv
from discord.ext import commands
import random
from discord import Game
import discord
import json
load_dotenv()
TOKEN = 'TOKENHERE'
GUILD = os.getenv('DISCORD_GUILD') # Same thing but gets the server name
bot = commands.Bot(command_prefix='r!')
on = "I'm up and running!"
print("Booting up...")
cmds = ["r!test - responds with: I hear you!"]
channel2 = bot.get_channel(CHANNELID)
#bot.event # idk what this means but you have to do it
async def on_ready(): # when the bot is ready
for guild in bot.guilds:
if guild.name == GUILD:
break
print(
f'{bot.user} has connected to Discord! They have connected to the following server: ' # client.user is just the bot name
f'{guild.name}(id: {guild.id})') # guild.name is just the server name
channel2 = bot.get_channel(703869904264101969)
global amounts
try:
with open('amounts.json') as f:
amounts = json.load(f)
except FileNotFoundError:
print("Could not load amounts.json")
amounts = {}
await channel2.send(on)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="r!help"))
#bot.command(name='test', help='Responds with: I can hear you! Used mainly for testing. ')
async def test(ctx):
await ctx.send("I hear you!")
#bot.command(name='ping', help='Tells you the latency of the bot.')
async def ping(ctx):
await ctx.send("Pong! " + str(int(bot.latency) * 1000) + "ms!")
#bot.command(name='say or simonsays', help='Responds with whatever you say after.', aliases = ['say', 'simonsays'])
async def say(ctx, *, contents: str):
await ctx.send(contents)
#bot.command(name='diceroll', help='Rolls a dice!')
async def diceroll(ctx, number_of_dice: int, number_of_sides: int):
dice = [
str(random.choice(range(1, number_of_sides + 1)))
for i in range(number_of_dice)
]
await ctx.send(', '.join(dice))
#bot.event
async def on_member_join(member):
await channel2.send(f'{member} has joined the server.')
#bot.event
async def on_member_remove(member):
await channel2.send(f'{member} has left the server. F')
#bot.command(name='coolnotcool', help='Tells you whether you are cool or not.')
async def coolnotcool(ctx, *, member: str):
coolornot = random.choice(range(1, 3))
if coolornot == 1:
await ctx.send(f'{member} is cool.')
elif coolornot == 2:
await ctx.send(f'{member} is not cool.')
#bot.command(name='8ball', help='Ask it a question and it will respond')
async def eightball(ctx, question):
answers=['It is certain.', 'Without a doubt.', 'You may rely on it.', 'Yes, definitely.', 'It is decidedly so.', 'As I see it, yes.', 'Most likely.', 'Yes.', 'Outlook good.', 'Signs point to yes.', 'Reply hazy, try again.', 'Better not tell you now.', 'Ask again later.', 'Cannot predict now.', 'Concentrate, then ask again.', 'Dont count on it.', 'Outlook not so good.', 'My sources say no.', 'Very doubtful.', 'My reply is no.']
response = random.choice(range(1, 21))
await ctx.send(str(answers[response]))
#bot.command(name='coinflip', help='Responds with either heads or tails. Good for making a decision.')
async def coinflip(ctx):
answer = random.choice(range(1, 3))
if answer == 1:
await ctx.send('Heads!')
else:
await ctx.send('Tails!')
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Please pass in all required arguments.')
bot.run(TOKEN)
#bot.command(pass_context=True, name='bal', help='Shows you how many rb you have in the bank.')
async def bal(ctx):
id = str(ctx.message.author.id)
if id in amounts:
await ctx.send("You have {} in the rb bank".format(amounts[id]))
else:
await ctx.send("You do not have an account yet. Type r!register to register!")
#bot.command(pass_context=True, name='register', help='Register to start using RuinBot currency!')
async def register(ctx):
id = str(ctx.message.author.id)
if id not in amounts:
amounts[id] = 100
await ctx.send("You are now registered! Remember, type r!save to save!")
_save()
else:
await ctx.send("You already have an account.")
#bot.command(name='save', help='Your currency autosaves, but remember to always save just in case! This saves your currency.')
async def save(ctx):
_save()
await ctx.send("Data saved!")
#bot.command(pass_context=True, name='give', help='Give another member some rb!')
async def give(ctx, amount: int, other: discord.Member):
primary_id = str(ctx.message.author.id)
other_id = str(other.id)
if primary_id not in amounts:
await ctx.send("You do not have an account")
elif other_id not in amounts:
await ctx.send("The other party does not have an account")
elif amounts[primary_id] < amount:
await ctx.send("You cannot afford this transaction")
else:
amounts[primary_id] -= amount
amounts[other_id] += amount
await ctx.send("Transaction complete")
_save()
def _save():
with open('amounts.json', 'w+') as f:
json.dump(amounts, f)
If anyone could help with this, that would be great. The .json file is empty.
The empty json file is your error. Edit the json file so that it contains the following:
{}