I have a rewrite version discord.py.If message have content, error does not happened.I need that error does not happened if message have not content.
My code:
#client.command(pass_context = True)
def async search(ctx,message):
...
some code
...
if members_count < voice_channel.user_limit:
message.content += ' '
print(message.content)
invite = await channel.create_invite(max_age=0)
avatar = user.avatar_url
if message == '':
message_for_emb = '\u200b'
elif message != '':
message_for_emb = ':white_small_square: {}'.format(message)
if user.default_avatar_url == avatar:
avatar = 'https://i.imgur.com/XjeDXnB.png'
embed = discord.Embed(description=members, colour=discord.Embed.Empty)
embed.set_author(name='В поисках +{} в {} {}'.format((voice_channel.user_limit - members_count),
voice_channel.category.name,voice_channel.name), icon_url=avatar)
embed.add_field(name=message_for_emb,
value='Зайти: {} :white_check_mark:'.format(invite.url), inline=False)
await channel.send(embed=embed)
Full traceback:
Ignoring exception in command search:
Traceback (most recent call last):
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\bot.py", line 886, in invoke
yield from ctx.command.invoke(ctx)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 491, in invoke
yield from self.prepare(ctx)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 455, in prepare
yield from self._parse_arguments(ctx)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 369, in _parse_arguments
transformed = yield from self.transform(ctx, param)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 249, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: message is a required argument that is missing.
The way commands parse arguments means that defining
async def search(ctx, message):
means that search requires a word message as part of the command invocation. If you instead want to capture the remainder of the message, you can use the keyword-only argument syntax:
async def search(ctx, *, message)
This feature is documented here.
Related
So I've been making a warning system in d.py and I'm finally on my last command is a clearwarn command which will.. Clear a warn of a user. However I want to be able to delete the document with the mongodb document's _id or if none is provided, then it'll delete all the warns that matches the user's id
#client.hybrid_command(name = "clearwarn", with_app_command=True, description="Delete a warn or all warns of a member", aliases=["clearwarns"])
#commands.guild_only()
#commands.has_permissions(moderate_members=True)
async def clearwarn(ctx, member: discord.Member = None, caseid = None):
if member == None:
await ctx.reply("A member is required")
else:
if caseid == None:
check = list(warndb.warn_logs.deleteMany({"user_id": member.id}))
if check is None:
await ctx.reply("This user doesn't have any warns to clear")
else:
await ctx.reply(f"Removed all warnings from **{member.name}**")
return
else:
try:
warndb.warn_logs.deleteOne({_id:ObjectId(caseid)}, True)
await ctx.reply(f"Removed 1 warning from **{member.name}**")
return
except:
await ctx.reply("The case id you provided is invalid")
return
caseid would be the _id from mongodb, I also don't know how to delete a document.
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "/home/container/main.py", line 418, in clearwarn
check = list(warndb.warn_logs.deleteMany({"user_id": member.id}))
File "/home/container/.local/lib/python3.9/site-packages/pymongo/collection.py", line 3213, in __call__
raise TypeError(
TypeError: 'Collection' object is not callable. If you meant to call the 'deleteMany' method on a 'Collection' object it is failing because no such method exists.
I want to make a role assignment using the support approval on the discord server, in general, a complex system.. To do this, I need to save the message id and the id of the message author who needs to be assigned a role, all the code is working, an error in the line of code associated with the database.
event code
cluster = MongoClient('mongodb+srv://corry:pa4-pD6-3Dj-AdT#cluster0.gi8x6.mongodb.net/?retryWrites=true&w=majority')
db = cluster.RolesData
roles = db.RolesCollection
#bot.event
async def on_message(message):
msg = message.content.lower()
request = ['роль', 'хочу роль', 'дайте роль', 'нужна роль']
if msg in request:
for i in orgs:
if not message.author.display_name.split(' ')[0].replace('[', '') in orgs:
await message.channel.send(f'`[ROLES]`: {message.author.mention}, тег организации не найден!')
break
if i == message.author.display_name.split(' ')[0].replace('[', ''):
guild = bot.get_guild(831511376425123882)
role = discord.utils.get(guild.roles, id=orgs[i])
await message.channel.send(f'`[ROLES]`: {message.author.mention}, ваш запрос на получение роли был отправлен саппортам!')
embed = discord.Embed(
title='Запрос на получение роли!',
description='✅ - выдать роль\n❌ - отклонить запрос\n🖊️ - изменить никнейм\n📋 - запросить статистику',
color=0x000000
)
embed.add_field(name=f'Пользователь:', value=f'{message.author.mention}', inline=False)
embed.add_field(name=f'Никнейм:', value=f'{message.author.display_name}', inline=False)
embed.add_field(name=f'Роль для выдачи:', value=f'{role.mention}', inline=False)
embed.set_thumbnail(url='https://psv4.userapi.com/c537232/u356224017/docs/d1/416eb92aec38/rodina.png?extra=2E9CwKZ0PIjnG8aaNkwehlHwjxlycBfGx-4p20ABm3mPI4jNpdV1OXaUUA9zGA4Q04VM21UezrXsjtqC411Xbh-Ro7rW1L4OGgNxpcQv3lvfOYCb-Irn-_-51AaQa2fpNDZhHm80dvZm1HlR1ZWoDigw')
embed.set_image(url=message.author.avatar_url)
msgemb = await bot.get_channel(851413212485779466).send(embed=embed)
await msgemb.add_reaction('✅')
await msgemb.add_reaction('❌')
await msgemb.add_reaction('🖊️')
await msgemb.add_reaction('📋')
roles_post = {
'm_id':msg_db.id,
'user':msg_db.author
}
if roles.count_documents({'m_id':message.id}) == 0:
roles.insert_one(roles_post)
else:
await message.channel.send(f'`[ROLES]`: {message.author.mention}, вы уже отправили запрос на получение роли!')
error code
Traceback (most recent call last):
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 89, in _resolve_uri
results = _resolve(
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 43, in _resolve
return resolver.resolve(*args, **kwargs)
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\resolver.py", line 1305, in resolve
return get_default_resolver().resolve(qname, rdtype, rdclass, tcp, source,
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\resolver.py", line 1176, in resolve
timeout = self._compute_timeout(start, lifetime)
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\resolver.py", line 997, in _compute_timeout
raise Timeout(timeout=duration)
dns.exception.Timeout: The DNS operation timed out after 21.201510190963745 seconds
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Хозяин\Desktop\rodina\main.py", line 5, in <module>
cluster = MongoClient('mongodb+srv://corry:pa4-pD6-3Dj-AdT#cluster0.gi8x6.mongodb.net/?retryWrites=true&w=majority')
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\mongo_client.py", line 704, in __init__
res = uri_parser.parse_uri(
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\uri_parser.py", line 542, in parse_uri
nodes = dns_resolver.get_hosts()
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 121, in get_hosts
_, nodes = self._get_srv_response_and_hosts(True)
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 101, in _get_srv_response_and_hosts
results = self._resolve_uri(encapsulate_errors)
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 97, in _resolve_uri
raise ConfigurationError(str(exc))
pymongo.errors.ConfigurationError: The DNS operation timed out after 21.201510190963745 seconds
Для продолжения нажмите любую клавишу . . .
Judging by this bit self._raise_connection_failure(error) in your error message, I believe the issue lies within the fact that you're not successfully connecting to your db in the first place.
I get a new error now. I edited smth now and i get this error. What to do. New code is given below
#commands.command()
async def warn(self, ctx, user:discord.Member, *, reason=None):
user_id = user.id
if collection.count_documents({"userid":user.id}) == 0:
collection.insert_one({"userid":user.id,"count":0})
if reason == None:
return await ctx.send("Please mention a reason!")
elif user == None:
return await ctx.send("Please mention a member!")
user = collection.find_one({"userid":user.id})
current_count = user["count"]
new_count = current_count + 1
collection.update_one({"userid":user.id}, {"$set": {"count": new_count}})
em = discord.Embed(title = "Member Warned!", description = f"Warned {user.mention} for **{reason}** | They now have {new_count} warnings!", timestamp = ctx.message.created_at, color = 0xFF0000)
em.set_footer(text=f'Warned By {ctx.author} | ID: {ctx.author.id}', icon_url = ctx.author.avatar_url)
await ctx.send(embed = em)``` This is the code
Ignoring exception in command warn:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/HorribleSentimentalParallelprocessing/cogs/warn.py", line 30, in warn
collection.update_one({"userid":user.id}, {"$set": {"count": new_count}})
AttributeError: 'dict' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'id'```
You are trying to find the user without any warnings. You were also adding warnings to the author himself instead of the user.
#commands.command()
async def warn(self, ctx,user: discord.Member, *,reason=None):
if collection.count_documents({"userid":user.id}) == 0:
collection.insert_one({"userid":user.id,"count":0})
if reason is None:
return await ctx.send("Please mention a reason!")
user_doc = collection.find_one({"userid":user.id})
current_count = user_doc["count"]
new_count = current_count + 1
collection.update_one({"userid":user.id}, {"$set": {"count": new_count}})
em = discord.Embed(title = "Member Warned!", description = f"Warned {user.mention} for **{reason}** | They now have {new_count} warnings!", timestamp = ctx.message.created_at, color = 0xFF0000)
em.set_footer(text=f'Warned By {ctx.author} | ID: {ctx.author.id}')
collection.update_one({"userid":ctx.author.id}, {"$inc": {"count": 1}})
await ctx.send(embed = em)
So I'm developing discord bot with discord.py for my server. I'm using replit's database system. When I try to add instance of my class Player to key of that database it says:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 36, in jointothefun
db[f"{context.message.author.id}"] = p
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 486, in __setitem__
self.set(key, value)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 495, in set
self.set_raw(key, _dumps(value))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 56, in dumps
return json.dumps(val, separators=(",", ":"), cls=DBJSONEncoder)
File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
return cls(
File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
ValueError: Circular reference detected
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: Circular reference detected
I have no idea why it's not working at all. Some one could help?
Oh and source code (yes i know i'm making spaghetti code)
Main file for bot
from discord.ext import commands
from replit import db
from alive import startup
from playerclass import Player
print(db.keys())
class PlayerClient(discord.Client):
async def on_member_join(self,member):
print(f"{member} joined")
async def on_ready(self):
print("Bot ready to work!")
def __init__(self):
self.intents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)
self.bot = commands.Bot(command_prefix = '~rpg ', intents = intents)
intents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)
client = bot = commands.Bot(command_prefix = '~rpg ', intents = intents)
#client.command(name='join')
async def jointothefun(context):
keys = db.keys()
rpgc = client.get_channel(811518285634863124)
if context.message.channel == rpgc:
if not f"{context.message.author.id}" in keys:
await context.message.channel.send("Hi "+str(context.message.author.mention))
#not working code
db[f"{context.message.author.id}"] = Player(100,0,0,0,0,1)
else:
await context.message.channel.send("Bruh you've joined already")
else:
await context.message.channel.send('Yo wrong channel!')
#client.command(name='stats')
async def stats(context):
rpgc = client.get_channel(811518285634863124)
if context.message.channel==rpgc:
keys = db.keys()
if str(context.message.author.id) in keys:
embed=db[str(context.message.author.id)].displayEquipment
await context.send(embed=embed)
else:
await context.message.channel.send("Join first to access stats!")
else:
await context.message.channel.send(f"XD {context.message.author.mention} to nie ten kanał! Pisz na #rpg")
#client.command()
async def ping(ctx):
await ctx.send("Pong!")
startup()
#yes i know that will not work but it's private i guess it's obvious
client.run("my bot token")
Player class
from item_class import Weapon
import discord
class Player:
def __init__(self,h,m,de,c,t,dm):
self.hp=h
self.mana=m
self.defense=de
self.coins=c
self.truecoins=t
self.weapon=Weapon("Stick",10,1,1,100,1,0)
self.dmg=dm+self.weapon.dmg
self.itlist=[]
def addItemToEq(self,it):
self.itlist.append(it)
def displayEquipment(self,client,context):
embed = discord.Embed(
title="Inventory",colour=discord.Colour.Green)
for i in self.itlist:
if type(i)==Weapon:
embed.add_field(i.self.name,"Weapon",False)
else:
embed.add_field(i.self.name,"Item",False)
return embed
Item class
import random
class Item:
def __init__(self,name):
self.name = name
def use(self):
print("its normal item bruh")
class Food(Item):
def __init__(self,name,nutrition):
self.name=name
self.hpboost=nutrition
class Weapon(Item):
def __init__(self,name,durablity,dmgboost,critchcmin,critchcmax,crit,boost):
self.name=name
self.durablity=durablity
self.dmg=dmgboost
self.critmin=critchcmin
self.critmax=critchcmax
self.critdmg=crit
self.fnc=boost
def attack(self):
print(self.dmg)
print(str(self.calcCrit()))
self.durablity-=1
def calcCrit(self):
if random.randint(self.critmin,self.critmax)<=self.critmax/2:
return True
else:
return False
def useBoost(self):
self.boost()
I would be so grateful if someone would help me :)
as answered here, the values of replit's database must be JSON-serializable. This means, you'd have to pass (most likely) a dict instead of a class object, but then you won't be able to use the object's functions.
Anything in Replit's database has to be JSON serializable. (Str, int, float, list, etc)
You could save the important properties as a json to the database. (e.g "name": "stick", "durablity": 10, "dmg": 1)
Please read to the bottom before answering.
My code loads the JSON from a file called reference.json. Then it adds different object to file, then dumps it back to the file. But when it does that return this error:
Ignoring exception in command import:
Traceback (most recent call last):
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 120, in attach_command
self.dump_json(json_content, new_file, new_channel, message=message)
File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
reference_content = json.load(reference_file)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
JSON file:
{}
Coding Snippet:
def dump_json(self, json_content, new_file, channel, message=None):
if new_file:
reference_file = open("json/reference.json", "w+")
reference_content = json.load(reference_file)
reference_content[str(channel.name)] = {}
reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
reference_content[str(channel.name)]["channel_id"] = int(channel.id)
reference_content[str(channel.name)]["message_id"] = int(message.id)
json.dump(reference_content, reference_file, indent=4)
file = open(f"json/{channel.name}.json", "w")
json.dump(json_content, file, indent=4)
Full Code:
from discord.ext import commands
from os import path
import utils
import discord
import json
class ImportTestSuite(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def get_json_content(self, ctx):
attachments = ctx.message.attachments
if len(attachments) == 0:
embed = discord.Embed(description="You need to provide 1 JSON attachment",
timestamp=ctx.message.created_at,
colour=discord.colour.Colour.red())
embed = utils.add_promotion_footer(embed)
await ctx.send(embed=embed)
return None
attachment = attachments[0]
if attachment.filename.split(".")[1] != "json":
embed = discord.Embed(description="You must attach a `.json` file",
timestamp=ctx.message.created_at,
colour=discord.colour.Colour.red())
embed = utils.add_promotion_footer(embed)
await ctx.send(embed=embed)
return None
attachment_content = await attachment.read()
try:
json_content = json.loads(attachment_content)
except json.JSONDecodeError:
embed = discord.Embed(description="You must attach valid JSON.\nUse "
"https://jsonformatter.curiousconcept.com/ or an alternative to"
" validate JSON",
timestamp=ctx.message.created_at,
colour=discord.colour.Colour.red())
embed = utils.add_promotion_footer(embed)
await ctx.send(embed=embed)
return None
return json_content
def dump_json(self, json_content, new_file, channel, message=None):
if new_file:
print(message)
print(channel.id)
reference_file = open("json/reference.json", "w+")
reference_content = json.load(reference_file)
reference_content[str(channel.name)] = {}
reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
reference_content[str(channel.name)]["channel_id"] = int(channel.id)
reference_content[str(channel.name)]["message_id"] = int(message.id)
json.dump(reference_content, reference_file, indent=4)
file = open(f"json/{channel.name}.json", "w")
json.dump(json_content, file, indent=4)
async def setup_new_channel(self, ctx, channel):
new_channel = await channel.category.create_text_channel(channel.name,
overwrites=channel.overwrites,
position=channel.position,
topic=channel.topic,
nsfw=channel.is_nsfw())
await channel.delete()
embed = discord.Embed(description="React with ✅ to start the test",
timestamp=ctx.message.created_at,
colour=discord.colour.Colour.green())
embed = utils.add_promotion_footer(embed)
message = await new_channel.send(embed=embed)
await message.add_reaction("✅")
return message, new_channel
def check_if_new_file(self, channel):
new_file = False
if not path.exists(f"json/{channel.name}.json"):
new_file = True
return new_file
#commands.command(name="import")
async def attach_command(self, ctx, channel: discord.TextChannel = None):
if channel is None:
channel = ctx.message.channel
json_content = await self.get_json_content(ctx)
if json_content is None:
return
new_file = self.check_if_new_file(channel)
if new_file:
message, new_channel = await self.setup_new_channel(ctx, channel)
self.dump_json(json_content, new_file, new_channel, message=message)
else:
await ctx.message.delete()
self.dump_json(json_content, new_file, channel)
def setup(bot):
bot.add_cog(ImportTestSuite(bot))
I have tried different modes and checked if the data is correct, all that is good.
Thanks in advance
The cause is given in this other SO post: Confused by python file mode "w+".
but not closing as duplicate because is may not be evident at first sight.
The error stack trace gives the line in your code that raises the error:
File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
reference_content = json.load(reference_file)
Just before, we can find:
reference_file = open("json/reference.json", "w+")
As explained in the referenced post, w+ mode truncates the file to 0 length, and json does not read your initialized data but an empty file and finds nothing since char 0, hence the error message.