Discord Python Rewrite - Custom Server Prefixes Error - python

I tried these code
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(float)
return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix = get_prefix)
#client.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(float)
prefixes[str(guild.id)] = ','
with open('prefixes.json', 'w') as f:
json.dump(prefixes, float, indent=4)
#client.event
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefixes.json', 'w') as float:
json.dump(prefixes, float, indent=4)
#client.command()
#commands.has_permissions(manage_channels=True)
async def prefix(ctx, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix changed succesfully, now my prefix for this server is: "{prefix}"')
and i got these erors
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", >line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 943, in on_message
await self.process_commands(message)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 939, in process_commands
ctx = await self.get_context(message)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 853, in get_context
prefix = await self.get_prefix(message)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 798, in get_prefix
ret = await discord.utils.maybe_coroutine(prefix, self, message)
File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line >331, in maybe_coroutine
value = f(*args, **kwargs)
File "C:\Users\PC\Desktop\Code\Project 01\index.py", line 20, in get_prefix
return prefixes[str(message.guild.id)]
KeyError: '744103149471662152'
Please help, it was working a few weeks ago.

The server ID is not in the JSON File
Add it manually OR Kick the bot from that server and re-invite it again

Ok. First, you are running json.loads(float). Float is a function, not the file. I edited the code you posted, try using this:
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix = get_prefix)
#client.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = ','
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
#client.event
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
#client.command()
#commands.has_permissions(manage_channels=True)
async def prefix(ctx, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix changed successfully, now my prefix for this server is: "{prefix}"')
(I also fixed some spelling errors in your messages)
If that still gives you the error, kick the bot and re-invite. Should work then.

def get_prefix(client, message):
with open('./database/prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
you did right load float instead of writing f
and check if the server id in the json file
try edit it manual or kick the bot and invite it again

Uhh your code may be right but just use f instead of float
But IG the problem is that you have not put {} in your JSON file so it is not taking that input.

Related

Discord.py: Expecting value: line 1 column 1 (char 0)

I'm trying to make a bot that re-adds the "muted" role to whoever rejoined the server while muted. Here's the .py code:
#bot.event
async def on_member_join(member):
with open('users.json', 'r') as fp:
data = json.load(fp)
mute = discord.utils.get(member.guild.roles, name = "mute role")
if member.id in data['muted']:
await member.add_roles(mute)
class Moderation(commands.Cog):
#bot.command()
async def mute(ctx, member:discord.Member):
mute = ctx.guild.get_role(THE ROLE'S ID)
await member.edit(roles=[mute])
with open('users.json', 'r+') as fp:
data = json.load(fp)
if member.id not in data['muted']:
data['muted'].append(member.id)
json.dump(data, fp)
And here's the .json code:
{
"muted" : []
}
Every time I mute someone, I get an error saying "JSONDecodeError: Expecting value: line 1 column 1 (char 0)" and the person's ID won't save. I've looked on many other posts for answers but none of them answered anything.
When you open with r+ and read it, you're now seeking to the end. Then, when you write to it, you're actually appending to the file rather than overwriting it.
You can see the behavior here:
>>> with open('_delete_me.txt', 'w') as f:
... f.write('this is a test.')
...
15
>>> with open('_delete_me.txt', 'r+') as f:
... print(f.read())
... f.write('another test')
...
this is a test.
5
>>> with open('_delete_me.txt', 'r') as f:
... print(f.read())
...
this is a test.another test
To overwrite it, it's possible to just open the file again in w write mode:
with open('users.json', 'r') as fp:
data = json.load(fp)
if member.id not in data['muted']:
data['muted'].append(member.id)
with open('users.json', 'w') as fp:
json.dump(data, fp)

How to save user id only once in json file discord.py

The code I have saves the same user in the json file again:
#client.command()
async def Shibaku1(ctx, coin1, coin2, coin3, coin4, coin5, coin6):
with open('Shibaku1.json', 'r') as f:
coins_data = json.load(f)
coins_data[ctx.author.id] = (coin1, coin2, coin3, coin4, coin5, coin6)
with open('Shibaku1.json', 'w') as f:
json.dump(coins_data, f)
I tried making an if statement in order to not happen, but it didn't seem to work
Python automatically updates keys in dictionary if they exist.
You should convert ctx.author.id to str using str(ctx.author.id):
#client.command()
async def Shibaku1(ctx, coin1, coin2, coin3, coin4, coin5, coin6):
with open('Shibaku1.json', 'r') as f:
coins_data = json.load(f)
coins_data[str(ctx.author.id)] = (coin1, coin2, coin3, coin4, coin5, coin6)
with open('Shibaku1.json', 'w') as f:
json.dump(coins_data, f)

Command SetPrefix and Json? Discord py

First:
I wanted to add more functions to my bot so that I created a new folder where I would try new things!
Second:
I wanted to add a command to set a prefix!
Third:
I added a prefix.json file and a start.bat to start the bot next to the bot.py
Fourth:
TROUBLE!
When writing the script with more than 1280 likes, the bat and the python file did not load, they both closed
Fifth:
The script!
import discord
import json
from discord.ext import commands
def get_prefix(bot, message):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(guild.id)] = '.'
token = 'Private (-:'
bot = commands.Bot(command_prefix='c:', help_command=None)
#bot.event
async def on_ready():
print('Ya estoy')
#bot.event
async def on_guild_join(guild):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = '.'
with open('prefix.json', 'w') as f:
json.dump(prefixes, f, indent=4)
#bot.event
async def on_guild_remove(guild):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefix.json', 'w') as f:
json.dump(prefixes, f, indent=4)
#bot.command()
async def setprefix(ctx, prefix):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open('prefix.json', 'w') as f:
json.dump(prefixes, f, indent=4)
bot.run(token)
First: What's the problem there?
Second: your get_prefix function needs to be passed into the command_prefix of Bot
code:
def get_prefix(bot, message):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
bot = commands.Bot(command_prefix=get_prefix, help_command=None)
Third: what's the issue with your bat file?
fourth: I'm not sure what your bat is doing and what you're doing with it.

Write a CSV file asynchronously in Python

I am writing a CSV file with the following function:
import csv
import os
import aiofiles
async def write_extract_file(output_filename: str, csv_list: list):
"""
Write the extracted content into the file
"""
try:
async with aiofiles.open(output_filename, "w+") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=columns.keys())
writer.writeheader()
writer.writerows(csv_list)
except FileNotFoundError:
print("Output file not present", output_filename)
print("Current dir: ", os.getcwd())
raise FileNotFoundError
However, as there is no await allowed over writerows method, there are no rows being written into the CSV file.
How to resolve this issue? Is there any workaround available?
Thank you.
Entire code can be found here.
You can use aiocsv. Here is a quick example of writing a row to a CSV file asynchronously:
import asyncio
import aiofiles
from aiocsv import AsyncWriter
async def main():
async with aiofiles.open('your-path.csv', 'w') as f:
writer = AsyncWriter(f)
await writer.writerow(['name', 'age'])
await writer.writerow(['John', 25])
asyncio.run(main())
For more examples follow: https://pypi.org/project/aiocsv/
In my opinion it’s better not to try to use the aiofiles with the csv module and run the synchronous code using loop.run_in_executor and wait it asynchronously like below:
def write_extract_file(output_filename: str, csv_list: list):
"""
Write the extracted content into the file
"""
try:
with open(output_filename, "w+") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=columns.keys())
writer.writeheader()
writer.writerows(csv_list)
except FileNotFoundError:
print("Output file not present", output_filename)
print("Current dir: ", os.getcwd())
raise FileNotFoundError
async def main():
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, write_extract_file, 'test.csv', csv_list)
You can use aiofiles, you just gotta convert the dict to a row :)
import aiofiles
async def write_extract_file(
output_filename: str, csv_list: list
):
cols = columns.keys()
async with aiofiles.open(output_filename, mode='w+') as f_out:
await f_out.write(','.join(cols)+'\n')
for data in csv_list:
line = []
for c in cols:
line.append(str(data[c]) if c in data else '')
line = ','.join(line) + '\n'
await f_out.write(line)

how to check if id exist in json

each time i use .register it will keep just making the account and not checking the id exist and if it does it will say the account is already made.
i've tryed if ctx.author.id not in jsonfile
and geting it from the file with other code too
just too much too add
#bot.command()
#commands.has_permissions(manage_guild=True)
async def register(ctx):
with open('Configs/amounts.json') as f:
usersidlel = json.loads(f.read())
if ctx.message.author.id not in usersidlel:
with open('Configs/amounts.json') as f:
data = json.loads(f.read())
data[str(ctx.author.id)] = {}
data[str(ctx.author.id)]['cash'] = 100
data[str(ctx.author.id)]['bank'] = 100
data = json.dumps(data, indent=4, sort_keys=True)
with open('Configs/amounts.json', 'w') as f:
f.write(data)
await ctx.send(f"```Account Registered!```")
else:
await ctx.send(f"Hey {ctx.author.name} you already got an account you silly person!")
No error messages just not sure how to check if the id exist or not.
You're testing a different variable than you're adding. Also, if ctx.author.id is an integer, you need to convert it to a string before testing.
There's also no need to load the JSON twice, just use the data returned by the first load.
async def register(ctx):
with open('Configs/amounts.json') as f:
usersidlel = json.load(f)
if str(ctx.author.id) not in usersidlel:
usersidlel[str(ctx.author.id)] = {'cash': 100, 'bank': 100}
with open('Configs/amounts.json', 'w') as f:
json.dump(usersidlel, f, indent=4, sort_keys=True)
await ctx.send(f"```Account Registered!```")
else:
await ctx.send(f"Hey {ctx.author.name} you already got an account you silly person!")

Categories