I would like to make a bot with bank accounts but it says that user is not defined. I watched a lot of tutorials and searched around but I could not find a solution :O I am new and really not good at python I would appreciate every help.
#client.command()
async def balance(ctx):
user = ctx.author
await open_account(user)
users = await get_bank_data(ctx)
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
await ctx.send(bank_amt)
async def open_account(ctx, user):
users = await get_bank_data(ctx)
with open("mainbank.json", "r") as f:
users = json.load(f)
if str(user.id) in users:
return False
else:
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open("mainback.json", "w") as f:
json.dump(users,f)
return True
async def get_bank_data(ctx):
with open("mainbank.json", "r") as f:
users = json.load(f)
return users
Not sure about 'user' not defined error in that code. But I see a lot of other things are wrong in there.
await open_account(user), this line is incorrect. The definition of open_account makes it clear that it takes two argument, yet you only pass one argument to it. This should throw "Missing one Required Positional Argument 'user'" which is also probably the error you are getting
with open("mainback.json", "w") as f: I am pretty sure you made a typo here, 'mainbank' instead of 'mainback'.
async def get_bank_data(ctx), this function apparently takes an argument but does not use it. I am sure you know that function don't necessarily need an argument to be called. Also I don't understand why this function is a coroutine when there is no need for it to be.
Similarly, open_account need not be a coroutine as well. It also takes a ctx which is quite useless as it just uses that to pass onto get_ban_data which is useless as the function doesn't utilize it, as mentioned in point 3.
Related
So I'm trying to make a command that adds the name of a song to an user. I just don't understand how I should do that. I tried looking on the dictionary documentations but I couldn't find anywhere how I could append a variable to a certain person. This is my current code altough I think it's completely wrong:
#commands.command()
async def quote(self, ctx):
await ctx.send("add your quote")
msg = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
quote = msg.content
with open('quotes.json', 'r') as f:
quotes = json.load(f)
quotes.append(quote)
with open('quotes.json', 'w') as f:
json.dump(quotes, f)
await ctx.send("quote added!")
You can use this with a dictionary and track them by ID. Be careful with this, as JSON does not allow you to use integers as keys to anything. Only strings are allowed.
#commands.command()
async def quote(self, ctx):
await ctx.send("add your quote")
msg = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
quote = msg.content
with open('quotes.json', 'r') as f:
quotes = json.load(f)
strid = str(msg.author.id) # this is necessary for json
if strid not in quotes.keys():
quotes[strid] = []
quotes[strid].append('My quote, or put whatever you need to add in here')
with open('quotes.json', 'w') as f:
json.dump(quotes, f)
await ctx.send("quote added!")
As a sidenote, it's a bad idea to open the file and close it multiple times. Instead, you can try a construct like this, and then you will be spared from opening the file so much:
client = commands.Bot(...)
with open('quotes.json', 'r'):
client.quotes_data = json.load(f)
#tasks.loop(minutes=3.0) # adjust this at your liking, or execute it manually
async def save_all():
with open('quotes.json', 'w'):
json.dump(client.quotes_data, f)
save_all.start()
If you're trying to make it so users can request multiple songs in a queue type fashion, I'd create a dictionary, make the key the user (the message's author)'s ID (ctx.author.id) and set the value to an empty list, then append to that list the user's requested song's name.
On the other hand, if you prefer one song per user, just set the value to the song for the user's ID's key.
This would typically use just casual key assignments for dictionaries.
An example of how this would work (assume this is inside your command):
songs = {};
# This code if you'd like multiple songs per user.
songs[ctx.author.id] = [];
songs[ctx.author.id].append("SONG VALUE HERE");
# This code if you'd like one.
songs[ctx.author.id] = "SONG VALUE HERE";
Sorry for the unclear question title. I don't know any other way to put it.
I made a command that says p!channel [channel_id] which basically makes a channel where my bot will respond with "e". I want the command to store the channel_id and guild_id into a json file called channel.json, and when a user sends a message, it will check if the message is in the channel_id channel, and if it is in the channel, will send "e". However, it's not responding and no error codes are showing up. Can someone help? Code is below:
def get_channel(client,message):
with open("channel.json", "r") as f:
e = json.load(f)
return e[str(message.guild.id)]
#client.command()
#commands.has_permissions()
async def channel(ctx, *, channelid):
with open("channel.json", "r") as f:
e = json.load(f)
e[str(ctx.guild.id)] = channelid
with open("channel.json", "w") as f:
json.dump(e,f)
await ctx.send(f"Successfully setup <#{channelid}>")
#client.event
async def on_message(message):
if message.channel.id == get_channel:
await message.channel.send('e')
There are several immediate problems that are keeping this from functioning.
You're only referencing get_channel, not calling it. The channel's ID isn't equal to the function itself, so the message is never sent. You want get_channel(client, message).
Your on_message event ensures that your command never gets called.
You attempt to use ctx.send() instead of ctx.channel.send().
Channel IDs are integers, but command arguments are always read in as strings. Without converting the argument to an integer, comparing it against a channel's ID will always return False.
In addition, there are several things you could improve:
The get_channel function doesn't ever use client, so you could alter your function definition to simply get_channel(message).
Furthermore, channel IDs are globally unique, so you don't need to save the guild ID in order to unambiguously identify a channel.
It would be more efficient not to read the whole file every time you need to check for an ID.
The has_permissions check doesn't check anything if you supply it no arguments, so in your code it does nothing.
You probably don't want your bot to respond to its own messages.
Here's an improved version that reads a saved file on startup, if one exists. It then keeps the IDs as a set in memory, and only opens the file when it needs to add a new ID.
from discord.ext import commands
import json
client = commands.Bot(command_prefix='p!')
try:
with open('channels.json') as f:
client.ids = set(json.load(f))
print("Loaded channels file")
except FileNotFoundError:
client.ids = set()
print("No channels file found")
#client.command()
async def channel(ctx, channel_id):
try:
channel_id = int(channel_id)
except ValueError:
await ctx.channel.send("Channel must be all digits")
return
if channel_id in client.ids:
await ctx.channel.send(f"Channel <#{channel_id}> is already set up.")
return
client.ids.add(channel_id)
with open('channels.json', 'w') as f:
json.dump(list(client.ids), f)
await ctx.channel.send(f"Successfully set up <#{channel_id}>")
#client.event
async def on_message(message):
if message.channel.id in client.ids and message.author != client.user:
await message.channel.send('e')
# Pass processing on to the bot's command(s)
await client.process_commands(message)
client.run(TOKEN)
What I'm trying to implement in my discord bot is a system that stops a running command coroutine as soon as another command is invoked by the same user, in an attempt to sort of keep a unique active session for each user.
So essentially I need to be able to access that coroutine object and stop it from within another coroutine.
What I've tried so far looks logic to me but I'm sure there is some misconception about how discord API handles coroutines. Here's a basic example:
active_sessions = {}
#bot.command()
async def first_command(ctx):
# Saving the coroutine in the dictionary with the user ID as key:
active_sessions[ctx.author.id] = ctx.command.callback
# do stuff
#bot.command()
async def second_command(ctx):
# Accessing the coroutine object and trying to stop it.
try:
coro = active_sessions[ctx.author.id]
coro.close()
except KeyError:
pass
which throws an AttributeError stating that function object has no attribute close.
But, as per discord.py docs, command.callback refers to a coroutine object that should have the close method. Also tried coro.cancel() with the same result.
I'm conceptually doing something wrong here but I'm not sure what exactly, and also I have no clue how to implement my idea correctly, so any help is very appreciated.
EDIT
So, since my goal might still be unclear, here is what I'm trying to accomplish.
I'm doing a discord bot that is sort of a game. Users can run several commands, many of which would wait for a certain amount of time for a reaction or message from the command author.
But this user might run another command without 'completing' the first one, and if they come back to the first, their reactions would still be accepted.
I'm trying to avoid this behaviour and keep the user focused on a 'single session'; whatever command they run, the execution of the previous one needs to be automatically stopped.
So how I'm implementing this, which comes from a wrong misconception of coroutines, is having a dictionary that associates each user with the loop of the command thy're currently running. If another loop starts with the other one still running, the 'old loop' would be stopped and the respective entry in the dictionary would be updated with the new loop:
active_sessions = {}
#bot.command()
async def first_command(ctx):
# In this first command I want to assign the current loop to a variable and
# add it to the active_sessions dictionary along with the ID of the command author.
# Then there's a loop that waits for user's reaction.
# Ignore the details such as the check function.
while True:
try:
reaction, user = await bot.wait_for("reaction_add",timeout=60,check=check)
# some if conditions here make the bot behave differently according
# to the specific reaction added
except asyncio.TimeoutError:
return
#bot.command()
async def second_command(ctx):
# As soon as this second command is invoked, I need to access the 'loop object'
# previously stored in the dictionary (if any) and stop it from here.
There are two ways to actually stop the wait_for from working.
Switching to a bot event.
import json
#bot.event()
async def on_reaction_add(reaction, user):
# use a config variable
with open('config.json', 'r') as f:
data = json.load(f)
if data['wait_for_reaction']:
# do stuff here
else:
return
#commands.command()
async def activate(ctx):
#activates the listenere
with open('config.json', 'r') as f:
data = json.load(f)
data['wait_for_reaction'] = True
with open('config.json', 'w') as f:
json.write(data, f, indent=4)
await ctx.send('activated listener')
#commands.command()
async def deactivate(ctx):
with open('config.json', 'r') as f:
data = json.load(f)
data['wait_for_reaction'] = False
with open('config.json', 'w') as f:
json.write(data, f, indent=4)
await ctx.send('activated listener')
You can also use a global variable or a .env file to load the config variable
Using a task
from discord.ext import tasks
#tasks.loop(seconds=0)
async def task(ctx):
try:
reaction, user = await bot.wait_for("reaction_add",timeout=60, check=check)
except asyncio.TimeoutError:
return
#commands.command():
async def activate(ctx):
try:
task.start(ctx)
except RuntimeError:
await ctx.send("task is already running")
finally:
await ctx.send('started task')
#commands.command()
async def deactivate(ctx):
task.stop()
await ctx.send('stopped task')
The problem is tasks is that you can only run one task at once, so you cannot use the command in multiple contexts. There is a workaround but I wouldn't recommend using it. Use tasks only if your bot is a personal one that only you run.
References:
tasks
Note:
If you are going to use a .env file to store your variable. Look into dotenv
I am trying to create a command (<MF_add) that adds a point to member's json value and that only admins can use.
This is my code right now:
#client.command()
#commands.has_permissions(administrator = True)
async def MF_add(ctx, user: discord.Member):
with open ("MF Points.json", "r") as f:
users = json.load(f)
await client.get_user(user_id)
user = client.get_user(user_id)
if user in users:
users["{user.mention}"]["points"] += 1
await ctx.message.channel.send(f"You have given {member.mention} 1 MF point.")
with open("MF Points.json", "w") as f:
json.dump(users, f, indent = 4)
It's not giving any errors, but it's also completely unresponsive.
Thank you for any help!
First off I'd like to recommend you use SQLLite instead of JSON. JSON is not a database. You should really refrain from using it to store user data that can frequently change.
Regarding what you've currently got, JSON is used similar to a dictionary. It uses keys and values. I highly doubt that the if statement if user in users: is returning true. You should check (with a print statement) to see if the if statement is even working.
You don't actually make a command here, the #commands.has_permissions(administrator = True) is not what you use to make a new command. You need a #bot.command() in front of it like:
#bot.command()
#commands.has_guild_permissions(administrator=True)
async def MF_add(ctx, user: discord.Member):
with open ("MF Points.json", "r") as f:
users = json.load(f)
await client.get_user(user_id)
user = client.get_user(user_id)
if user in users:
users["{user.mention}"]["points"] += 1
await ctx.message.channel.send(f"You have given {member.mention} 1 MF point.")
with open("MF Points.json", "w") as f:
json.dump(users, f, indent = 4)
That would solve your question I believe, now to talk a bit about your program as it will not function like you expect it to, at all (or it'll just error):
client.get_user(userid) is not asyncronous and doesn't need to be awaited
you seem to never define user_id anywhere (as it is a variable)
why do you want to get the user again in the first place? You get the user from you parameters right?
["{user.mention}"] from when you look at the user's key is nothing but a string, you need to add an f in front of it for it to actually look for a mention value in user
ctx.message.channel.send can be shortened to ctx.send
f"You have given {member.mention} 1 MF point." You never defined a member value
I've rewritten most of your code into something that should work I believe:
#bot.command()
#commands.has_guild_permissions(administrator=True)
async def MF_add(ctx, user: discord.Member):
with open ("MF Points.json", "r") as f:
users = json.load(f)
if str(user.id) in users:
users[str(user.id)] += 1
else:
users[str(user.id)] = 1
await ctx.send(f"You have given {user.mention} 1 MF point.")
with open("MF Points.json", "w") as f:
json.dump(users, f, indent = 4)
Note that not knowing what you actually want to achieve with this code/what other functions you want to introduce I'm not too sure this is the best way. But you should be able to figure things out with this as a basis
Note: I converted the keys to strings as json doesnt like int keys, you can use int keys if you use a custom object_hook though (I'll let you look into that, it probs isnt work looking into for the use case you have anyways)
I have made a system that uses JSON files to create a currency system with a discord bot using discord.py
I want users to be able to do +balance to show them how much they have, or +balance in order to check someone else's balance. I tried doing a try: to grab the members' balance and excepting if there was no argument for the member, but I don't know what kind of error it is for that. How do I make it so that the bot will assume if there is no argument that the member they want is ctx.message.author?
if exists('balances.json'):
with open('balances.json', 'r') as file:
balances = json.load(file)
print(balances)
def save():
with open('balances.json', 'w+') as f:
json.dump(balances, f)
#Allows users to check their balance
#bot.command(pass_context=True)
async def balance(ctx, member: discord.Member):
global balances
if str(member.id) not in balances.keys():
await ctx.channel.send(f'{member.name} not registered')
return
if str(member.id) in balances.keys():
requestedUserBalance = balances[str(member.id)]
await ctx.channel.send(f'{member.name} has {requestedUserBalance} LotusTokens')
To give a function a default behavior when an optional variable is not passed, you can give it a default value of None and a behavior when that variable is None.
#bot.command(pass_context=True)
async def balance(ctx, member: discord.Member=None):
if member is None:
member = ctx.message.author
# do stuff