I've got a working currency system, but we want ways to earn money. So i want to make mini games, so i made a coin flip game but i can't get it to work, it tells me the command is not found when i try it.I also want to make it so the game costs >currency so you can win a little bit so basically betting
from discord.ext import commands
import discord
import json
import random
from discord.ext.commands import Bot
from discord import Game
import time
import asyncio
bot = commands.Bot('$')
amounts = {}
#bot.event
async def on_ready():
global amounts
try:
with open('amounts.json') as f:
amounts = json.load(f)
except FileNotFoundError:
print("Could not load amounts.json")
amounts = {}
#bot.command(pass_context=True)
async def balance(ctx):
id = str(ctx.message.author.id)
if id in amounts:
await ctx.send("You have {} :Ereb: in the bank".format(amounts[id]))
else:
await ctx.send("You do not have an account")
#bot.command(pass_context=True)
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")
_save()
else:
await ctx.send("You already have an account")
#bot.command(pass_context=True)
async def transfer(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)
#bot.command()
async def save():
_save()
***#bot.command() #problem
async def on_message(message):
if message.content.startswith('$coinflip'):
randomlist = ["heads","tails",]
await client.send_message(message.channel,(random.choice(randomlist)))***
bot.run("token")
```
You need to decorate your on_message callback with bot.event instead of bot.command. You also need to add a bot.process_commands line so that the other commands are invoked normally.
#bot.event
async def on_message(message):
if message.content.startswith('$coinflip'):
randomlist = ["heads","tails",]
await client.send_message(message.channel,(random.choice(randomlist)))
else:
await bot.process_commands(message)
Related
I come with a problem that I can't solve despite several attempts, and when I enter the .balance or .work command, there is no message and error log in the console.
main.py:
import discord
from discord.ext import commands
from webserver import keep_alive
import json
import os
os.chdir("/home/runner/exidexi")
intents = discord.Intents.all()
client = commands.Bot(command_prefix=".", intents=intents, case_insensitive=True)
client.remove_command('help')
#client.event
async def on_ready():
await client.change_presence(activity=discord.Game('.pomoc'))
print("Bot is currently online!")
#client.event
async def setup_hook():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await client.load_extension(f'cogs.{filename[:-3]}')
print(f"Loaded Cog: {filename[:-3]}")
else:
print("Unable to load pycache folder.")
keep_alive()
token = os.environ.get("discord_bot_secret")
client.run(token)
economy.py:
import discord
from discord.ext import commands
import datetime
import random
import json
import os
class balance(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("economy.py is ready!")
#commands.command()
async def balance(self, ctx):
await open_account(ctx.author)
users = await get_bank_data()
user = ctx.author
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
embed = discord.Embed(title = f"{ctx.author.name}'s balance",color = discord.Color.red())
embed.add_field(name = "Wallet balance",value = wallet_amt)
embed.add_field(name = "Bank balance",value = bank_amt)
await ctx.reply(embed = embed)
#commands.command()
async def work(self, ctx):
await open_account(ctx.author)
users = await get_bank_data()
user = ctx.author
earnings = random.randrange(101)
await ctx.reply(f"Someone gave you {earnings} coins!!")
users[str(user.id)]["wallet"] += earnings
with open("mainbank.json","w") as f:
json.dump(users,f)
async def open_account(user):
users = await get_bank_data()
user = ctx.author
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("mainbank.json","w") as f:
json.dump(users,f)
return True
async def get_bank_data():
with open("mainbank.json","r") as f:
users = json.load(f)
return users
async def setup(client):
await client.add_cog(economy(client))
in mainbank.json:
{
}
I saw similar questions, but there was at least one error, but i dont have at least one. However, I tried to do as written, but nothing helped. I also tried removing await and async with open_account and get_bank_data but it didnt help.
I am having troubles gettimg my commands to work, it keeps telling me that they do not exist when they clearly do. I've been stumped on this for hours and can't figure out why its not working. I've tried doing commands.command() instead of #commands.command(), but no luck, i tried explicitly defining the name of the command #commands.command(name="play") but still no luck
import youtube_dl
import pafy
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
#bot.event
async def on_ready():
print(f"{bot.user.name} is ready.")
bot.run("....")
class Player(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.song_queue = {}
self.setup()
def setup(self):
for guild in self.bot.guilds:
self.song_queue[guild.id] = []
async def check_queue(self, ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def search_song(self, amount, song, get_url=False):
info = await self.bot.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({"format" : "bestaudio", "quiet" : True}).extract_info(f"ytsearch{amount}:{song}", download=False, ie_key="YoutubeSearch"))
if len(info["entries"]) == 0: return None
return [entry["webpage_url"] for entry in info["entries"]] if get_url else info
async def play_song(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel, please connect to the channel you want the bot to join.")
if ctx.voice_client is not None:
await ctx.voice_client.disconnect()
await ctx.author.voice.channel.connect()
#commands.command()
async def leave(self, ctx):
if ctx.voice_client is not None:
return await ctx.voice_client.disconnect()
await ctx.send("I am not connected to a voice channel.")
#commands.command(name="play")
async def play(self, ctx, *, song=None):
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
# handle song where song isn't url
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for song, this may take a few seconds.")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I could not find the given song, try using my search command.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"I am currently playing a song, this song has been added to the queue at position: {queue_len+1}.")
else:
return await ctx.send("Sorry, I can only queue up to 10 songs, please wait for the current song to finish.")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
#commands.command()
async def search(self, ctx, *, song=None):
if song is None: return await ctx.send("You forgot to include a song to search for.")
await ctx.send("Searching for song, this may take a few seconds.")
info = await self.search_song(5, song)
embed = discord.Embed(title=f"Results for '{song}':", description="*You can use these URL's to play an exact song if the one you want isn't the first result.*\n", colour=discord.Colour.red())
amount = 0
for entry in info["entries"]:
embed.description += f"[{entry['title']}]({entry['webpage_url']})\n"
amount += 1
embed.set_footer(text=f"Displaying the first {amount} results.")
await ctx.send(embed=embed)
#commands.command()
async def queue(self, ctx): # display the current guilds queue
if len(self.song_queue[ctx.guild.id]) == 0:
return await ctx.send("There are currently no songs in the queue.")
embed = discord.Embed(title="Song Queue", description="", colour=discord.Colour.dark_gold())
i = 1
for url in self.song_queue[ctx.guild.id]:
embed.description += f"{i}) {url}\n"
i += 1
embed.set_footer(text="Thanks for using me!")
await ctx.send(embed=embed)
#commands.command()
async def skip(self, ctx):
if ctx.voice_client is None:
return await ctx.send("I am not playing any song.")
if ctx.author.voice is None:
return await ctx.send("You are not connected to any voice channel.")
if ctx.author.voice.channel.id != ctx.voice_client.channel.id:
return await ctx.send("I am not currently playing any songs for you.")
poll = discord.Embed(title=f"Vote to Skip Song by - {ctx.author.name}#{ctx.author.discriminator}", description="**80% of the voice channel must vote to skip for it to pass.**", colour=discord.Colour.blue())
poll.add_field(name="Skip", value=":white_check_mark:")
poll.add_field(name="Stay", value=":no_entry_sign:")
poll.set_footer(text="Voting ends in 15 seconds.")
poll_msg = await ctx.send(embed=poll) # only returns temporary message, we need to get the cached message to get the reactions
poll_id = poll_msg.id
await poll_msg.add_reaction(u"\u2705") # yes
await poll_msg.add_reaction(u"\U0001F6AB") # no
await asyncio.sleep(15) # 15 seconds to vote
poll_msg = await ctx.channel.fetch_message(poll_id)
votes = {u"\u2705": 0, u"\U0001F6AB": 0}
reacted = []
for reaction in poll_msg.reactions:
if reaction.emoji in [u"\u2705", u"\U0001F6AB"]:
async for user in reaction.users():
if user.voice.channel.id == ctx.voice_client.channel.id and user.id not in reacted and not user.bot:
votes[reaction.emoji] += 1
reacted.append(user.id)
skip = False
if votes[u"\u2705"] > 0:
if votes[u"\U0001F6AB"] == 0 or votes[u"\u2705"] / (votes[u"\u2705"] + votes[u"\U0001F6AB"]) > 0.79: # 80% or higher
skip = True
embed = discord.Embed(title="Skip Successful", description="***Voting to skip the current song was succesful, skipping now.***", colour=discord.Colour.green())
if not skip:
embed = discord.Embed(title="Skip Failed", description="*Voting to skip the current song has failed.*\n\n**Voting failed, the vote requires at least 80% of the members to skip.**", colour=discord.Colour.red())
embed.set_footer(text="Voting has ended.")
await poll_msg.clear_reactions()
await poll_msg.edit(embed=embed)
if skip:
ctx.voice_client.stop()
#commands.command()
async def pause(self, ctx):
if ctx.voice_client.is_paused():
return await ctx.send("I am already paused.")
ctx.voice_client.pause()
await ctx.send("The current song has been paused.")
#commands.command()
async def resume(self, ctx):
if ctx.voice_client is None:
return await ctx.send("I am not connected to a voice channel.")
if not ctx.voice_client.is_paused():
return await ctx.send("I am already playing a song.")
ctx.voice_client.resume()
await ctx.send("The current song has been resumed.")
async def setup():
await bot.wait_until_ready()
bot.add_cog(Player(bot))
bot.loop.create_task(setup())
You can try replacing :
async def setup():
await bot.wait_until_ready()
bot.add_cog(Player(bot))
bot.loop.create_task(setup())
With just :
bot.add_cog(Player(bot))
Moreover, put you run statement after all setup operations, so you have :
# Cog declaration
bot.add_cog(Player(bot))
bot.run('....')
run() should be executed as last function because it starts bot and it runs until you stop bot.
And all code which you have after run() is executed after you stop bot.
bot.loop.create_task(setup())
bot.run(TOKEN)
#commands.command()
Write this down where you wrote it down.
#bot.command()
Because:
bot = commands.Bot(command_prefix="!", intents=intents)
Since you have assigned a "bot" variable here, the name of the variable is added first, and then the "command" is added.
So I'm trying to make a music bot which just joins,plays,stops and resume music. However my bot can join and leave a voice channel fine, however when i do my /play command it get stuck on [youtube] oCveByMXd_0: Downloading webpage (this is output in vscode) and then does nothing after. I put some print statement (which you can see in the code below and it prints 1 and 2 but NOT 3). Anyone had this issue?
MUSIC BOT FILE
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def join(self, ctx):
if(ctx.author.voice is None):
await ctx.reply("*You're not in a voice channel.*")
voiceChannel = ctx.author.voice.channel
if(ctx.voice_client is None): # if bot is not in voice channel
await voiceChannel.connect()
else: # bot is in voice channel move it to new one
await ctx.voice_client.move_to(voiceChannel)
#commands.command()
async def leave(self, ctx):
await ctx.voice_client.disconnect()
#commands.command()
async def play(self,ctx, url:str = None):
if(url == None):
await ctx.reply("*Check your arguments!*\n```/play VIDEO_URL```")
else:
ctx.voice_client.stop() # stop current song
# FFMPEG handle streaming in discord, and has some standard options we need to include
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YTDL_OPTIONS = {"format":"bestaudio"}
vc = ctx.voice_client
# Create stream to play audio and then stream directly into vc
with youtube_dl.YoutubeDL(YTDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
print("1")
url2 = info["formats"][0]["url"]
print("2")
source = await discord.FFmpegOpusAudio.from_probe(url2,FFMPEG_OPTIONS)
print("3")
vc.play(source) # play the audio
await ctx.send(f"*Playing {info['title']} -* 🎵")
#commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.reply("*Paused -* ⏸️")
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.reply("*Resuming -* ▶️")
def setup(bot):
bot.add_cog(music(bot))
MAIN FILE
from discord.ext import commands
from dotenv import load_dotenv
from lxml import html
import youtube_dl
import requests
import random
import discord
import requests
import os
import music
# Load .env file
load_dotenv()
COGS = [music]
PREFIX = "/"
bot = commands.Bot(command_prefix=PREFIX, intents=discord.Intents.all())
for x in range(len(COGS)):
COGS[x].setup(bot)
# EVENTS #
#bot.event
async def on_ready():
await bot.get_channel(888736019590053898).send(f"We back online! All thanks to *sploosh* :D")
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
replies = ["Err is that even a command?", "Can you type bro?", "Yeah... thats not a command buddy.", "Sorry forgot you can't spell"]
await ctx.send(random.choice(replies))
#bot.event
async def on_message(message):
if str(message.channel) == "images-videos" and message.content != "":
await message.delete()
await bot.process_commands(message)
# COMMANDS #
#bot.command()
async def hello(ctx):
# Get a random fact
url = 'http://randomfactgenerator.net/'
page = requests.get(url)
tree = html.fromstring(page.content)
hr = str(tree.xpath('/html/body/div/div[4]/div[2]/text()'))
await ctx.reply("**Hello Bozo!**\n" + "*Random Fact : *" + hr[:-9]+"]")
#bot.command()
async def randomNum(ctx, start:int = None, end:int = None):
if(start == None or end == None):
await ctx.reply("*Check your arguments!*\n```/randomNum START_NUMBER END_NUMBER```")
else:
randNum = random.randint(start, end)
await ctx.reply(f"*{randNum}*")
#bot.command()
#commands.is_owner()
async def kick(ctx, member:discord.Member = None, *, reason="You smell bozo."):
if(member == None):
await ctx.reply("*Check your arguments!*\n```/kick #MEMBER REASON(optional)```")
elif ctx.author.id in (member.id, bot.user.id):
await ctx.reply("*You cant kick yourself/me you silly.*")
else:
await member.kick(reason=reason)
#bot.command()
#commands.is_owner()
async def ban(ctx, member:discord.Member = None, *, reason="Bye Bye! :D."):
if(member == None):
await ctx.reply("*Check your arguments!*\n```/kick #MEMBER REASON(optional)```")
elif ctx.author.id in (member.id, bot.user.id):
await ctx.reply("*You cant ban yourself/me you silly.*")
else:
await member.ban(reason=reason)
#bot.command()
#commands.is_owner()
async def close_bot(ctx):
replies = ["Well bye!", "Guess I go now?", "Please let me stay..."]
await ctx.send(random.choice(replies))
await bot.close()
if __name__ == "__main__":
bot.run(os.getenv("BOT_TOKEN"))
This is how my play music command is setup, and i know for sure it works and it seems like it should work for you too.
#commands.command()
async def play(self, ctx, *, song=None):
commandd = "play"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
# handle song where song isn't url
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for song, this may take a few seconds.")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I could not find the given song, try using my search command.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"I am currently playing a song, this song has been added to the queue at position: {queue_len+1}.")
else:
return await ctx.send("Sorry, I can only queue up to 10 songs, please wait for the current song to finish.")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
this is some other things that you might need
import discord
from discord.ext import commands
from random import choice
import string
from discord.ext.commands.cooldowns import BucketType
import asyncio
import youtube_dl
import pafy
import datetime
from discord_slash import cog_ext, SlashContext
x = datetime.datetime.now()
from ult import *
class music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.song_queue = {}
self.setup()
def setup(self):
for guild in self.bot.guilds:
self.song_queue[guild.id] = []
async def check_queue(self, ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
ctx.voice_client.stop()
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def search_song(self, amount, song, get_url=False):
info = await self.bot.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({"format" : "bestaudio", "quiet" : True}).extract_info(f"ytsearch{amount}:{song}", download=False, ie_key="YoutubeSearch"))
if len(info["entries"]) == 0: return None
return [entry["webpage_url"] for entry in info["entries"]] if get_url else info
async def play_song(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
I'm currently learning python (slowly) and have started writing a discord bot. However, when i call a #client.command function nothing happens in discord. For example .ping should reply with "pong!" but nothing happens and I do not get an error.
My code is below
import discord
from discord.ext import commands
import asyncio
import time
import discord.client
client = commands.Bot(command_prefix=".")
messages = joined = 0
bad_words = ["example"]
channel = ["general"]
#client.command()
async def kick(ctx, userName: discord.Member):
await client.kick(userName)
#client.event(message)
async def on_ready():
id = client.get_guild(705455096749752323)
print("hello")
async def update_stats():
await client.wait_until_ready()
global messages, joined
while not client.is_closed():
try:
with open("stats.txt", "a") as f:
f.write(f"""Messages: {messages}, Members Joined {joined}, time: {time.time()}\n""")
messages = 0
joined = 0
await asyncio.sleep(5)
except Exception as e:
print(e)
#client.event
async def on_member_update(before, after):
n = after.nick
if n:
if n.lower().count("Crysis Wolfie") > 0:
last = before.nick
if last:
await after.edit(nick=last)
else:
await after.edit(nick="NO STOP THAT!")
#client.event
async def on_member_update(before, after):
n = after.game
if n:
if n.lower.count(f"""{before.n}""") > 0:
discord.message.channel.send()
#client.event
async def on_member_join(member):
global joined
joined += 1
for channel in member.server.channels:
if str(channel) == "general":
await discord.message.channel_send(f"""Welcome to the server {member.mention}""")
#client.event
async def on_message(message, yes=None):
# chat commands
id = client.get_guild(705455096749752323)
channels = ["general", "apply"]
global messages
messages = + 1
if str(message.channel) in channels:
if message.content.find("!hello") != -1:
await message.channel.send(f"""What's cooking {message.author.mention} looking good today :wink:""")
elif message.content == "!users":
await message.channel.send(f"""Number of members {id.member_count}""")
if message.content.find("NHS") != -1:
await message.channel.send("https://tenor.com/view/goodjob-clap-nicework-great-gif-7248435")
if message.content.find("wolfie") != -1:
await message.channel.purge(limit=1)
await message.channel.send("https://tenor.com/view/facepalm-really-stressed-mad-angry-gif-16109475")
if message.content.find("crysis") != -1:
await message.channel.purge(limit=1)
await message.channel.send("https://tenor.com/view/facepalm-really-stressed-mad-angry-gif-16109475")
if message.content.find("!apply") != -1:
await message.channel.send(f"""TESTING""")
for word in bad_words:
if message.content.count(word) > 0:
await message.channel.purge(limit=1)
await message.channel.send(f"""User {message.author.mention} watch your language!""")
try:
with open("badwordlog.txt", "a") as n:
n.write(f"""member: {message.author}, said {message.content}, at {time.time()}\n""")
print(f"""member: {message.author}, said {message.content}""");
except Exception as e:
print(e)
await client.process_commands(message)
#client.event
async def on_member_update(before, after): # needs fixing
n = before.status
if n != before:
await discord.message.channel.send(f"""have fun on {after} """)
#client.command()
async def create_invite(self, ctx): # needs fixing
self = bot
"""Create invite"""
link = await ctx.channel.create_invite(max_age=300)
await ctx.send("Here is an instant invite to your server: " + link)
#client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
#client.command()
async def ping(ctx):
await ctx.send('pong!')
clint.run('my token is here but I have removed')
#client.event functions run fine and work great! But client.command does nothing :(.
thanks
When this code runs it works getting the user ID from discord and putting they have 100 money in the json, but once you restart the bot you have to register again and it writes the same user ID in the json file thinking it's a new user when it is not.
from discord.ext import commands
import discord
import json
bot = commands.Bot('!')
amounts = {}
#bot.event
async def on_ready():
global amounts
try:
with open('amounts.json') as f:
amounts = json.load(f)
except FileNotFoundError:
print("Could not load amounts.json")
amounts = {}
#bot.command(pass_context=True)
async def balance(ctx):
id = ctx.message.author.id
if id in amounts:
await ctx.send("You have {} in the bank".format(amounts[id]))
else:
await ctx.send("You do not have an account")
#bot.command(pass_context=True)
async def register(ctx):
id = ctx.message.author.id
if id not in amounts:
amounts[id] = 100
await ctx.send("You are now registered")
_save()
else:
await ctx.send("You already have an account")
#bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
primary_id = ctx.message.author.id
other_id = 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)
#bot.command()
async def save():
_save()
bot.run("Token")
JSON after the bot is turned off and back on and registered twice (fake user IDs):
{"56789045678956789": 100, "56789045678956789": 100}
Need it to be able to recognize the user IDs even after the bot is turned off and back on.
This is happening because JSON objects always have strings for the "keys". So json.dump converts the integer keys to strings. You can do the same by converting the user ids to strings before you use them.
from discord.ext import commands
import discord
import json
bot = commands.Bot('!')
amounts = {}
#bot.event
async def on_ready():
global amounts
try:
with open('amounts.json') as f:
amounts = json.load(f)
except FileNotFoundError:
print("Could not load amounts.json")
amounts = {}
#bot.command(pass_context=True)
async def balance(ctx):
id = str(ctx.message.author.id)
if id in amounts:
await ctx.send("You have {} in the bank".format(amounts[id]))
else:
await ctx.send("You do not have an account")
#bot.command(pass_context=True)
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")
_save()
else:
await ctx.send("You already have an account")
#bot.command(pass_context=True)
async def transfer(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)
#bot.command()
async def save():
_save()
bot.run("Token")
You just need to load the .json file that you have created at program startup. Instead of amounts = {} try this:
import os
if os.path.exists('amounts.json'):
with open('amounts.json', 'r') as file:
amounts = json.load(file)
else:
amounts = {} # default to not loading if file not found
UPDATE
I believe after reading your comment and reviewing your code the issue is in your register() code.
You have:
if id not in amounts:
But it should be:
if id not in amounts.keys():
I found out the problem and tested it myself, so it isn't the .keys() or the os thing, but in the _save() function. I first did a test with the _save function and without it, and instead of using a called on function, it worked when i did it manually. Like so
(P.S i did this within a cog, only difference is the name #commands.command, which is #bot.command and you need to add "self")
#commands.command(pass_context=True)
async def register(self, ctx):
id = str(ctx.message.author.id)
with open("smth.json") as json_file:
amounts = json.load(json_file)
if id not in amounts:
amounts[id] = 0
await ctx.send("You are now registered")
else:
await ctx.send("You already have an account!")
with open("smth.json", "w") as outfile:
json.dump(amounts, outfile)
ALSO VERY IMPORTANT NOTE, make sure when you create a json file, it's name ends with ".json" and all that's in it is
{
}