Good afternoon, I'm making a python bot in the aiogram library. Faced a problem, I created two inline keyboards and I have two menu buttons, one button should call the first inline keyboard and the second the second. But at startup it turns out that only the keyboard that is called first in the code is called, that is, in my code, "inline_button_menu" is called first, and the second does not react anymore. Help solve the problem.
Here is my code:
# Создание кнопок инлайн ---------------------------------------------------------------------
inline_btn_1 = InlineKeyboardButton('Сьогодні', callback_data='btn1')
inline_btn_2 = InlineKeyboardButton('На неділі', callback_data='btn2')
inline_btn_3 = InlineKeyboardButton('У цьому місяці', callback_data='btn3')
inline_btn_4 = InlineKeyboardButton('Останні 3 новини', callback_data='btn4')
inline_btn_5 = InlineKeyboardButton('Свіжі новини', callback_data='btn5')
# Инициализация кнопок(инлайн) ------------------------------------------------------------------------------------------
inline_button_menu = InlineKeyboardMarkup(row_width=2).add(
inline_btn_1).add(inline_btn_2).add(inline_btn_3)
inline_button_menu_2 = InlineKeyboardMarkup(row_width=2).add(
inline_btn_4).add(inline_btn_5)
# Кнопки меню(инлайн) ---------------------------------------------------------------------------------------------------
#dp.message_handler()
async def menu_birthday(message: types.Message):
# await bot.send_message(message.from_user.id, message.text)
if message.text == 'Дні народження':
await message.reply("Виберіть як подивитися дні народження: ",
reply_markup=inline_button_menu)
#dp.message_handler()
async def menu_news(message: types.Message):
# await bot.send_message(message.from_user.id, message.text)
if message.text == 'Новини':
await message.reply("Виберіть як подивитися новини: ",
reply_markup=inline_button_menu_2)
#dp.callback_query_handler(lambda c: c.data == 'btn4') # --------------------------- Последние три новости
async def process_callback_button1(callback_query: types.CallbackQuery):
await bot.answer_callback_query(callback_query.id)
with open("news_dict.json") as file:
news_dict = json.load(file)
for k, v in sorted(news_dict.items())[-3:]:
news = f"{hlink(v['article_title'], v['article_url'])}"
await bot.send_message(callback_query.from_user.id, news)
#dp.callback_query_handler(lambda c: c.data == 'btn5') # --------------------------- Свежие новости
async def process_callback_button1(callback_query: types.CallbackQuery):
await bot.answer_callback_query(callback_query.id)
fresh_news = check_news_update()
if len(fresh_news) >= 1:
for k, v in sorted(fresh_news.items()):
news = f"{hlink(v['article_title'], v['article_url'])}"
await bot.send_message(callback_query.from_user.id, news)
else:
await bot.send_message(callback_query.from_user.id, 'Свіжих новин немає')
#dp.callback_query_handler(lambda c: c.data == 'btn1') # -------------------------------------- Дни рождения
async def process_callback_button1(callback_query: types.CallbackQuery):
await bot.answer_callback_query(callback_query.id)
await bot.send_message(callback_query.from_user.id, 'Day: ')
Maybe too late, but
in your code there are two message handlers without any filters, so all your messages handled by this handler:
async def menu_birthday(message: types.Message):
For example you could add second condition to first function:
#dp.message_handler()
async def menu_birthday(message: types.Message):
if message.text == 'Дні народження':
await message.reply("Виберіть як подивитися дні народження: ",
reply_markup=inline_button_menu)
elif message.text == 'Новини':
await message.reply("Виберіть як подивитися новини: ",
reply_markup=inline_button_menu_2)
or you could have 2 separate handlers with text filters like this:
#dp.message_handler(text='Дні народження')
async def menu_birthday(message: types.Message):
await message.reply("Виберіть як подивитися дні народження: ", reply_markup=inline_button_menu)
#dp.message_handler(text='Новини')
async def menu_news(message: types.Message):
await message.reply("Виберіть як подивитися новини: ", reply_markup=inline_button_menu_2)
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))
I'm quite new to both Python and Discord.py, and I'm trying to find how to make the bot wait for either a message or reaction from user at the same time.
I tried separating each but just resulted in the bot needing a message response before a reaction.
Here's a similar code I'm trying to do:
#bot.event
async def on_message(ctx):
if ctx.author == bot.user:
return
if ctx.content == "$respond":
message = await ctx.send("Waiting for response...")
while True:
try:
response = #Will wait for a message(Yes or No) or reaction(Check or Cross) from ctx.author for 30 secs
except asyncio.TimeoutError:
await message.edit(content=f"{ctx.author} did not respond anymore!")
break
if response.content == "yes":
await message.edit(content=f"{ctx.author} said yes!")
continue
elif response.content == "no":
await message.edit(content=f"{ctx.author} said nyo!")
continue
#These are reactions
elif str(response.emoji) == "✅":
await message.edit(content=f"ctx.author reacted ✅!")
continue
elif str(response.emoji) == "❌":
await messave.edit(content=f"Stopped listening to responses.")
break
bot.wait_for is what you're looking for here.
I would recommend using bot.command() for command handling purposes but this is fine as well.
This is how you wait for specific events (provided as the first argument) with specific conditions (as provided in the check param)
#bot.event
async def on_message(msg):
if msg.author == bot.user:
# if the author is the bot itself we just return to prevent recursive behaviour
return
if msg.content == "$response":
sent_message = await msg.channel.send("Waiting for response...")
res = await bot.wait_for(
"message",
check=lambda x: x.channel.id == msg.channel.id
and msg.author.id == x.author.id
and x.content.lower() == "yes"
or x.content.lower() == "no",
timeout=None,
)
if res.content.lower() == "yes":
await sent_message.edit(content=f"{msg.author} said yes!")
else:
await sent_message.edit(content=f"{msg.author} said no!")
This would result in :
Listening for multiple events is a rather a bit interesting,
Replace the existing wait_for with this snippet :
done, pending = await asyncio.wait([
bot.loop.create_task(bot.wait_for('message')),
bot.loop.create_task(bot.wait_for('reaction_add'))
], return_when=asyncio.FIRST_COMPLETED)
and you can listen for two events simultaneously
Here's how you can handle this using #bot.command()
import discord
import os
from discord.ext import commands
bot = commands.Bot(command_prefix="$", case_insensitive=True)
#bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
#bot.command()
async def response(ctx):
sent_message = await ctx.channel.send("Waiting for response...")
res = await bot.wait_for(
"message",
check=lambda x: x.channel.id == ctx.channel.id
and ctx.author.id == x.author.id
and x.content.lower() == "yes"
or x.content.lower() == "no",
timeout=None,
)
if res.content.lower() == "yes":
await sent_message.edit(content=f"{ctx.author} said yes!")
else:
await sent_message.edit(content=f"{ctx.author} said no!")
bot.run(os.getenv("DISCORD_TOKEN"))
which would get you the same result.
Hey so when I type $opgg or $ftgopgg it will not come up with anything on the following
#bot.event
async def on_message(message):
if message.content('$opgg'):
response = 'Spend me the names'
await message.channel.send(response)
def check(m):
return m.author.id == message.author.id
opgg = await bot.wait_for('message')
await message.channel.send(f'https://oce.op.gg/multi/query={opgg.content.replace(" ", "%20")}')
print("done")
#bot.event
async def on_message(message):
if message.content == '$ftgopgg':
teamopgg = "https://oce.op.gg/multi/query=Disco Inferno, spranze, killogee, blank76, reeks"
await message.send(teamopgg.replace(" ", "%20"))
print("Tdone")
it was working like an hour ago but I could not use both commands, I don't know if I've gotten code work or if there is a mistake
You have 2 on_message events but discord.py supports only one.
If you are trying to create commands for your bot I recommend use #client.command() decorator instead of listening on_message event.
Something like:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="$", intents=discord.Intents.all())
#bot.command()
async def opgg(ctx):
response = "Spend me the names"
await message.channel.send(response)
def check(m):
return m.author.id == message.author.id
#bot.command()
async def ftgopgg(ctx):
teamopgg = "https://oce.op.gg/multi/query=Disco Inferno, spranze, killogee, blank76, reeks"
await message.send(teamopgg.replace(" ", "%20"))
print("Tdone")
bot.run("TOKEN")
If you want to use bot.command() and on_message event at the same time, you can use :
#bot.listen()
async def on_message(message):
instead of:
#bot.event
async def on_message(message):
Simple fix all i had to do was remove the lower #bot.event and async def on_message(message)
new code:
#bot.event
async def on_message(message):
if message.content('$opgg'):
response = 'Spend me the names'
await message.channel.send(response)
def check(m):
return m.author.id == message.author.id
opgg = await bot.wait_for('message')
await message.channel.send(f'https://oce.op.gg/multi/query={opgg.content.replace(" ", "%20")}')
print("done")
if message.content == '$ftgopgg':
teamopgg = "https://oce.op.gg/multi/query=Disco Inferno, spranze, killogee, blank76, reeks"
await message.send(teamopgg.replace(" ", "%20"))
print("Tdone")
DISCORD.PY
I try to create an command for a poll system and encounter a problem. Command is as follows:
#commands.command(pass_context = True)
async def poll(self, ctx, question, *options: str):
author = ctx.message.author
server = ctx.message.server
if not author.server_permissions.manage_messages: return await self.bot.say(DISCORD_SERVER_ERROR_MSG)
if len(options) <= 1:
await self.bot.say("```Error! A poll must have more than one option.```")
return
if len(options) > 2:
await self.bot.say("```Error! Poll can have no more than two options.```")
return
if len(options) == 2 and options[0] == "yes" and options[1] == "no":
reactions = ['👍', '👎']
else:
reactions = ['👍', '👎']
description = []
for x, option in enumerate(options):
description += '\n {} {}'.format(reactions[x], option)
embed = discord.Embed(title = question, color = 3553599, description = ''.join(description))
react_message = await self.bot.say(embed = embed)
for reaction in reactions[:len(options)]:
await self.bot.add_reaction(react_message, reaction)
embed.set_footer(text='Poll ID: {}'.format(react_message.id))
await self.bot.edit_message(react_message, embed=embed)
My question is: How can I make the question I ask using the command to have more words. If I use more words now, I read them as options and get an error.
Ex 1: /poll You are human yes no (only read "you" as a question, and the rest are options.)
Ex 2: /poll You are human yes no (that's what I want)
Thank you!
When calling the command, putting a string in quotes will cause it to be treated as one argument:
/poll "You are human" yes no
You can do:
#bot.command()
async def poll(ctx, question, option1=None, option2=None):
if option1==None and option2==None:
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \n{question}```\n**✅ = Yes**\n**❎ = No**")
await message.add_reaction('❎')
await message.add_reaction('✅')
elif option1==None:
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \n{question}```\n**✅ = {option1}**\n**❎ = No**")
await message.add_reaction('❎')
await message.add_reaction('✅')
elif option2==None:
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \n{question}```\n**✅ = Yes**\n**❎ = {option2}**")
await message.add_reaction('❎')
await message.add_reaction('✅')
else:
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \n{question}```\n**✅ = {option1}**\n**❎ = {option2}**")
await message.add_reaction('❎')
await message.add_reaction('✅')
but now you must do /poll hello-everyone text text
if you want to to not have the "-" you must do:
#bot.command()
async def poll(ctx, *, question):
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \n✅ = Yes**\n**❎ = No**")
await message.add_reaction('❎')
await message.add_reaction('✅')
But in this one you can't have your own options...
use :
/poll "You are human" yes no
here, "You are human" is one string "yes" "no" are other two strings.
another better way to do it is:
#commands.command(pass_context = True)
async def poll(self, ctx, option1: str, option2: str, *, question):
or, you can use wait_for
#commands.command(pass_context = True)
async def poll(self, ctx, *options: str):
...
question = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author)
...
it is working
#commands.has_permissions(manage_messages=True)
#commands.command(pass_context=True)
async def poll(self, ctx, question, *options: str):
if len(options) > 2:
await ctx.send('```Error! Syntax = [~poll "question" "option1" "option2"] ```')
return
if len(options) == 2 and options[0] == "yes" and options[1] == "no":
reactions = ['👍', '👎']
else:
reactions = ['👍', '👎']
description = []
for x, option in enumerate(options):
description += '\n {} {}'.format(reactions[x], option)
poll_embed = discord.Embed(title=question, color=0x31FF00, description=''.join(description))
react_message = await ctx.send(embed=poll_embed)
for reaction in reactions[:len(options)]:
await react_message.add_reaction(reaction)
#create a yes/no poll
#bot.command()
#the content will contain the question, which must be answerable with yes or no in order to make sense
async def pollYN(ctx, *, content:str):
print("Creating yes/no poll...")
#create the embed file
embed=discord.Embed(title=f"{content}", description="React to this message with ✅ for yes, ❌ for no.", color=0xd10a07)
#set the author and icon
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
print("Embed created")
#send the embed
message = await ctx.channel.send(embed=embed)
#add the reactions
await message.add_reaction("✅")
await message.add_reaction("❌")
for your code to treat the text in the user's message as one string, use "content:str" in your command arguments
I know my code isn't very dynamic and pretty but i did that and it's functional.
#client.command()
async def poll(ctx):
options = ['1️⃣ Yes Or No', '2️⃣ Multiple Choice']
embed = discord.Embed(title="What type of poll you want ?" , description="\n".join(options), color=0x00ff00)
msg_embed = await ctx.send(embed=embed)
reaction = await client.wait_for("reaction_add", check=poll)
if (reaction[0].emoji == '1️⃣'):
user = await client.fetch_user(ctx.author.id)
msg = await user.send("What is your question ?")
question = await client.wait_for("message", check=lambda m: m.author == ctx.author)
answers = ['\n\u2705 Yes\n', '\u274C No']
new_embed = discord.Embed(title="Poll : " + question.content, description="\n".join(answers), color=0x00ff00)
await msg_embed.edit(embed=new_embed)
await msg_embed.remove_reaction('1️⃣', user)
await msg_embed.add_reaction('\N{WHITE HEAVY CHECK MARK}')
await msg_embed.add_reaction('\N{CROSS MARK}')
elif (reaction[0].emoji == '2️⃣'):
user = await client.fetch_user(ctx.author.id)
msg = await user.send("What is your question ?")
question = await client.wait_for("message", check=lambda m: m.author == ctx.author)
msg = await user.send("What are the choices ? (Four compulsory choices, separated by comma)")
choices = await client.wait_for("message", check=lambda m: m.author == ctx.author)
choices = choices.content.split(',')
if (len(choices) > 4):
await msg_embed.delete()
await user.send("You can't have more than four choices")
return
if (len(choices) < 4):
await msg_embed.delete()
await user.send("You can't have less than four choices")
return
answers = ['1️⃣ '+ choices[0] + '\n', '2️⃣ '+ choices[1] + '\n', '3️⃣ '+ choices[2] + '\n', '4️⃣ '+ choices[3] + '\n']
new_embed = discord.Embed(title=question.content, description="\n ".join(answers), color=0x00ff00)
await msg_embed.edit(embed=new_embed)
await msg_embed.remove_reaction('2️⃣', user)
await msg_embed.add_reaction('1️⃣')
await msg_embed.add_reaction('2️⃣')
await msg_embed.add_reaction('3️⃣')
await msg_embed.add_reaction('4️⃣')
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:
{}