#General Help
1 messages · Page 18 of 1
ye i got that
you mean it's disabled?
or doesn't interact at all?
the buttons dont respond
can you send the code pls
see the issue is theres a lot of working parts but ill do my best
ah sry tunnel vision did not see your message under it xD
await interaction.followup.edit_message(view=self)
TypeError: edit_message() missing 1 required positional argument: 'message_id
class CountryApprovalView(discord.ui.View):
"""A view attached to country approval messages which adds an approve and deny button to the message."""
def __init__(self, user: discord.User, timeout):
super().__init__(timeout=timeout)
self._user = user
self.approver = None
self.reason = None
self.deleter = None
self.edit_interaction = None
...
@discord.ui.button(label="Edit", style=discord.ButtonStyle.blurple)
async def third_button_callback(self, button: discord.Button, interaction: discord.Interaction):
if self._user.id == interaction.user.id:
self.edit_interaction = interaction
self.stop()
else:
await interaction.response.send_message(f"You do not have permission to edit this claim!", ephemeral=True)
...
class PlayableAddModal(Modal):
...
async def callback(self, interaction: discord.Interaction): # TODO: Add ability to edit claims
embed = children_to_embed(self.children, self._entity, interaction.user)
approval_view = views.CountryApprovalView(interaction.user, timeout=None)
approval_channel_id = io.load_approve_channel(interaction.guild_id)
approval_channel = await interaction.guild.fetch_channel(approval_channel_id)
claim_msg = await approval_channel.send(embed=embed, view=approval_view)
await interaction.response.send_message(f"Claim successfully added! An admin will approve you in <#{approval_channel_id}>.", ephemeral=True)
await approval_view.wait()
approve_button = approval_view.children[0]
deny_button = approval_view.children[1]
edit_button = approval_view.children[2]
delete_button = approval_view.children[3]
orig_msg = await interaction.original_message()
...
elif approval_view.edit_interaction:
modal = EditClaimModal(self._fields, self._entity, embed, title="Edit your claim")
await approval_view.edit_interaction.response.send_modal(modal)
await modal.wait()
await claim_msg.edit(view=views.CountryApprovalView(interaction.user, timeout=None), embed=modal.embed)
class EditClaimModal(Modal):
def __init__(self, fields: Dict[str,List[InputText]], entity: str, embed: discord.Embed, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._fields = fields
self._entity = entity
self.embed = embed
for entity, list in self._fields.items():
if entity != "All" and entity != self._entity:
continue
for input_text in list:
for field in embed.fields:
if field.name.removesuffix(" Description") != input_text.label:
continue
input_text.value = field.value
break
self.add_item(input_text)
async def callback(self, interaction: discord.Interaction):
self.embed = children_to_embed(self.children, self._entity, interaction.user)
await interaction.response.send_message("Successfully edited claim!", ephemeral=True)
self.stop()
here are the relevant bits of code
it passes the button edit interaction from the view into the modal callback
I presume self.stop() makes the button not to be used?
self.stop() is what triggers await approval_view.wait() to stop waiting
so the code continues
at least, to my understanding that's what it does
the other buttons that work fine also have self.stop() in them
wait
no further interactions will be dispatched on this object
mihito that makes sense
how do i continue past self.wait() without self.stop()?
lemme try deleting the wait
ok deleting the stop and wait just breaks it
so it is needed
I also tried creating a new view and editing the message with the new view of the same type as the old view
but that also didnt work
I also dont like the callback hell comming with views.
My approach to this issue in my bots is to make an AwaitableView that all views inherit from.
In the base view there is a asnycio.Future that is set when a callback is executed you just have to await the future in your waiting code and boom es soon its set your main code executes.
Without needing to call .stop() so you could reuse the view if you want. I dont do that but it would be possible.
wym by the callback hell?
alot of callbacks
doesn't every button need a callback?
i can try to implement smth like that and see if it works
yea but i like to have my main logic in my command and not in button callbacks.
I dont want to jump with my logic from callback to callback.
the asyncio.Future approach modifies my views in a way that they only there for data grabbing and the data is returned back to my main command.
This way views are more modular and you can use the same view for other things even if the command logic is completely different.
i can see where you're coming from, this code is kinda spaghetti with how much everything jumps around
i just couldn't think of better ways to do it
my original solution was to have the view classes defined in the modal code but i don't think I can do that because I need to make the country approval view persistent
hm yea
because of how it works
it's just
a nightmare
the process of the command is:
use /claim, which sends a dropdown view
the dropdown options each send a modal
the modal then sends a message with a view to a different channel
when one of the buttons is clicked in the channel with the view, a message notifying the user is sent in the channel the claim was originally made in
any idea on how to get the Message ID on the message that the bot sent?
everything is working as intended except editing the claim message and also making the approval view consistent
ctx.respond() returns the message that was sent
iirc
or the interaction
you can get it from that
interaction = await ctx.respond("foo")
interaction.message.id
np
hours and hours of staring at the api trying to get code to work seems to be getting into my brain
honestly same
I have been learning pycord for about a week or 2 and the number of things are already clogging my brain 
xD
making it as user friendly as possible really adds an extra level of difficulty
True
Ah
it's a good project to put on my github
but we getting offtopic
we will get bonked
also yo wait
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_id: Value "<Authorising timeout=None children=2>" is not snowflake.
I got this error now after using
await interaction.followup.edit(view=self,message_id=self)
message_id=self?
yes, idk if I'm doing it correctly
Options = Authorising()
Options.message = await channel.send(role.mention, embeds=[embed],view = Options)
Options.id = Options.message.id
don't I need followup?
dont think so? try followup if that doesnt work
since I already used a response to send a modal
and you can't send modals using followups
can you send the full code? and what you are trying to do specifically?
let's go, that worked
basically, I sent a modal when the user interacted with a button and then at the same time I wanted to edit the message and disable the button
thanks!
btw why don't you use modals?
or dropdown menus
i meant as in for the button thing
ohh
well
it does
the edit button sends a modal with the fields filled in by default to match the existing claim message
so it "feels" like you're editing it more
oh so I believe that you want the button to the like more of the interaction staying at only one message thing?
can you please rephrase that?
all of the task is asyncronous but i think it does
always got discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction while background task is running
I presume that for the button that you want the user to interact
i believe you want it to be on the same message that it is on?
the same message that it is on?
e.g.
I'd change the message above the message and use the button that is there to be how the user interactions
I see hmm
I believe you need to set the interaction check as true and false as well
like where it says elif approval_view.edit_interaction:?
is the discord.Option "required" default to True or False
#How can I give someone rights to commands if they have rights to a voice channel?
Can someone help me?
for child in self.children:
if child is not button:
self.remove_item(child)
for some reason this doesn't remove all the buttons
it always leaves one
is it because self.children becomes smaller as you loop through it, thus skipping over elements?
yep that was it
fixed it by doing self.children = [button]
any ideas why cogs slash commands randomly stop working?
- I can verify the cogs are setup right
- if i move commands into my main.py (removing self etc) it works fine
- Slash commands DO show up. however i get "The application did not respond"
How can I get around embed fields having a character limit of 1024?
Field value limits are 1024 char, name 256, description is 4096. you can also only have 25 fields
There isnt rly a way to bypass unless u treat description as fields
does anyone know how to make a slash command only disabled in the dms but not in servers
guys, how many maximum number of embeds can i send via a paginator
thankyou
yeah I can’t find the examples
just annotate it as guild_only
any idea why it wont send this embed after hitting a button?
interaction.response.send_message(embed=embed)
hmm doesnt seem to work i can still run this command in dms
Hello !
I want to make a choose menu but i don't found it online so i came here to ask you
if u need code or informations ping or dm me !
Unions don't seem to work anymore for User/Member in release candidate 1, does anyone know why or a fix?
For example:
user: Option(typing.Union[discord.Member, discord.User], _("The user you want to unban."), required=True)
Returns:
TypeError: issubclass() arg 1 must be a class
how would you fix this
reduce length of text
so how does a bit get away with this
how to create global slash commands (in all servers that the bot is in)
Don't specify guild_id when making slash command

how do you put a link button in a class without a callback?
anyone know how to find the inviter everytime someone join a guild?
You have to check if an inviters list of invitees includes the user
guild.invites returns a list of invites in the guild. Than every time a use joins find what invite count increased than find the author
Why do slash commands become invalid after being run once and requiring bot to restart
Also do not ping random people for help
Can you show your code please
Also make sure you are on the latest version 2.0.0rc1
import discord
from discord.ext import commands
from discord.ext import bridge
import pymysql
import yaml
# Discord Bot Section
with open('token.txt','r',encoding='utf8') as tokenfile:
token = tokenfile.read().strip()
bot = discord.Bot(prefix='.',intents=discord.Intents.all())
@bot.event
async def on_ready():
pass
@bot.slash_command(guild_ids=[some_guild_id])
async def test(ctx,var1):
# await ctx.respond(f'{ctx.interaction.channel.name}\n{ctx.interaction.message}')
await ctx.interaction.channel.send(f'test\n{var1}')
await ctx.delete()
bot.run(token)
yes I am on that version
Do you want to use prefix or bridge?
no if slash commands work properly
Try removing the discord.ext import commands import
Commented the import bridge and commands, issue persists
So after running it once the next time you use the slash command it says "The command did not respond" or something similar
Do you only want slash commands or are you planning on using bridge to have both prefix and slash?
Only slash would be fine as I am writing a new bot from the ground up
is there a better way to add the buttons to the embed?
Ok Bridge is kind of buggy sometimes so I think that is a fair decision. I show you a few things you need to change in a moment
Ok, ping me in that message as well so that I will be able to find it, thanks
You can delete the 2 imports you have commented out. Also remove the prefix kwarg from the bot constructor.
Also makes sure that you do not have discord.py installed (or any other python discord bot lib)
Pip showed that I have discord.py installed.
I ran sudo pip3 uninstall discord.py
Now it is telling me that module discord has no attribute bot
What do you mean better way? No, I don't see one, you have to create a view to add the buttthat handle send the message. Also you did not use self.clear() so the other buttons will still be there if that is not what you want
Restart your IDE. If that does not work uninstall and than reinstall pycord. For some reason it gets buggy when you don't uninstall d.py before installing pycord.
Hey how i can block mass DM raid?
wdym?
Seems to start up correctly now, going to test the command issue
keep getting this error
its a given that both packages break when you install two packages that use the same namespace
Issue persists after making the changes, removing discord.py and reinstalling pycord 2.0.0rc1
First time command runs fine, after that it becomes invalid
If someone start a raid and send everyone on my server a DM. How can I block that?
you need Button and not button (uppercase)
I gtg i would open a thread
Same to you @upbeat hill
You can't do that with a bot.
And you can't really block that afaik.
But you can take certain measures to prevent people from raiding your server.
First would be the Moderation setting of you server.
And actually I can't think of more right now xD
@slender lintel
Yeah you can't detect someone send DMs to server users. You could have a report command though.
Is there an Option to only show Threads, and not all Channels?
What setting?
Ohhh..
Servereinstellungen -> Moderation
Welche Stufe?
Wie du willst. Höchste ist am sichersten aber auch am stressigsten für normale Nutzer. Musst nen gutes zwischending finden.
Okay danke
np
Channel slash options seem to be broken in 2.0.0b7
Is it save to upgrade to 2.0.0rc1 or does it have any breaking changes ?
Nope it works fine
@commands.Cog.listener()
async def on_application_command_error(self, ctx: discord.ApplicationContext, error: Exception):
if type(error) is discord.errors.ApplicationCommandInvokeError:
error: discord.errors.ApplicationCommandInvokeError
if type(error.original) is PlayerNotPlaying:
return await ctx.interaction.response.send_message('Nenhuma sala desse jogador foi encontrada!',
ephemeral=True)
if type(error.original) is ProfileNotPublic:
return await ctx.interaction.response.send_message(
'Seu perfil não é público! os comandos não irão funcionar!',
ephemeral=True)
if type(error.original) is NoLobbies:
return await ctx.interaction.response.send_message('Nenhuma sala no momento!', ephemeral=True)
I want to know why this is still printing to stderr?
it is handling the error, but still printing to stderr
you dont overwrite the listiner that is present in discord.Bot
All listeners are dispatched not just one.
And the one in discord.Bot prints to stderr
override bot and everride the mehtod to return
anyone know how to make a url button in sub-class view?
seems i cant make it with the decorator
@discord.ui.button(label='official', url='link')
async def btn2(self, button, interaction):
pass
that makes sense
just call self.add_item in init and construct the button yourself
class CustomBot(discord.Bot):
async def on_application_command_error(self, context: discord.ApplicationContext, exception: discord.DiscordException) -> None:
if self.extra_events.get("on_application_command_error", None):
return
command = context.command
if command and command.has_error_handler():
return
cog = context.cog
if cog and cog.has_error_handler():
return
tried this and i'm still getting the same issue
How can I make my bot react to every new msg in a channel with name
hm
Try to just return none without any logic
and you initiating custom bot ?
Not an other instance ?
yes
not really as long you dont have a error handler that prints to stderror
do a print in the handler please an look if it gets dispatched
every cog has a listener attached to on_application_command_error but none of them prints to stderr
on the cog? it is getting dispatched since I am getting the error messages my bot is supposed to send to the user
ok
well, the stderr output is coming from somewhere else then
I just don't know where
can you show full traceback ?
you know... it's actually not printing how it's supposed to print if it was on_application_command_error
what
ignoring exception IN on_application_command_error
how is that possible
@commands.Cog.listener()
async def on_application_command_error(self, ctx: discord.ApplicationContext, error: Exception):
if type(error) is discord.errors.ApplicationCommandInvokeError:
error: discord.errors.ApplicationCommandInvokeError
if type(error.original) is PlayerNotPlaying:
return await ctx.interaction.response.send_message('Nenhuma sala desse jogador foi encontrada!',
ephemeral=True)
if type(error.original) is ProfileNotPublic:
return await ctx.interaction.response.send_message(
'Seu perfil não é público! os comandos não irão funcionar!',
ephemeral=True)
if type(error.original) is NoLobbies:
return await ctx.interaction.response.send_message('Nenhuma sala no momento!', ephemeral=True)
there's my full handler
with the NoLobbies exception, it should run
return await ctx.interaction.response.send_message('Nenhuma sala no momento!', ephemeral=True)
and it is working
File "C:\Users\Diego\PycharmProjects\KajunRewrite\kajun\lobby_steam_init_.py", line 106, in lobbies
raise NoLobbies
The problem seems to be here.
Im not sure where the problem arraises but the traceback clearly says its in your error handler
that's where it's supposed to be raised
I thought the on_application_command_error would catch it
so that's not how it works?
yea it raises and the error handler is called.
that it gets raised in on_application_command_error again
what
You're using a listener cog. Cogs run with the "normal" listener present on the Discord.Bot instance. You're not overridering it.
we already got this one
on_application_command_error
yeah, I'm overrinding the original one on the bot
but I don't get how it is being raised again
"however it could be overridden to have a different implementation."
thats what you did
that's what I did and I'm still getting the stderr output
so it could be a bug on pycord itself then?
or the documentation is wrong
async def on_application_command_error(self, context: ApplicationContext, exception: DiscordException) -> None:
interface = ContextInterface(entity=context)
self.dispatch("handle_error", interface, exception)
I do it like this and it works like charm
So i dont think its a pycord problem
well, what I did was return None
i return none implicit its the same
if you dont return anything python will return None automaticly
What's wrong with it?
@bot.command()
async def pers(ctx):
category = bot.get_channel(985544678755663912)
if ctx.author.permissions_in(category).manage_channels:
await ctx.send(f"Perms test erfolgreich")
else:
await ctx.send(f"Nicht erfolgreich")
can you remove all cog on_errors for testing ?
And look if you still get an error ?
or if the bot just swollows it
how it should be
well... if I do that i'm gonna get an error, won't I?
since my errors are being handled on the cogs error handlers
if you overriding the default handler you should not
error ?
somitimes you have to bruteforce debugging xD
No error he does not react to it
you overriding the default handler ? for errors ?
removed the error handler on that cog, still getting stderr output
dafuq
I'm gonna run only that cog
this also exists but i dont override it either and i dont get stderr
so what the hell is happening
ahhhh
I don't use that one
this is not cog specific.
This is like registering a global error handler.
Now i understand you want the error to be cog specific.
this one is cog specifc
so by running only the cog I removed the error handler, the overridden method worked
But im no sure if this is working with app commandss
show code
I guess... I'm gonna have to rewrite a lot of code
@commands.Cog.listener()
async def on_cog_command_error (self, ctx: discord.ApplicationContext, error: Exception):
if type(error) is discord.errors.ApplicationCommandInvokeError:
error: discord.errors.ApplicationCommandInvokeError
if type(error.original) is PlayerNotPlaying:
return await ctx.interaction.response.send_message('Nenhuma sala desse jogador foi encontrada!',
ephemeral=True)
if type(error.original) is ProfileNotPublic:
return await ctx.interaction.response.send_message(
'Seu perfil não é público! os comandos não irão funcionar!',
ephemeral=True)
if type(error.original) is NoLobbies:
return await ctx.interaction.response.send_message('Nenhuma sala no momento!', ephemeral=True)
🤔
the also remove the on_ again
yeah
you need to override the method of the base cog
thank you, i won't have to spend 5h rewritting stuff
uninstall discord and discord.py and anything else what discord.py use
install pycord with
pip install py-cord==2.0.0rc1
PS C:\Users\Fammy\Desktop\keni> & C:/Users/Fammy/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Fammy/Desktop/keni/bot.py
Traceback (most recent call last):
File "c:\Users\Fammy\Desktop\keni\bot.py", line 1, in <module>
import discord
File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 25, in <module>
from .client import Client
File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 53, in <module>
from .webhook import Webhook
File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\__init__.py", line 12, in <module>
from .async_ import *
File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 52, in <module>
from ..channel import PartialMessageable
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py)```
did i downloaded wrong pycord version?
do you have discord.py still installed?
Slash commands become invalid when the context message is deleted
is prsaw still working for anyone
start cmd and type
pip show py-cord
How?
async def callback(self, interaction: discord.Interaction):
if self.children[0].value == "BESTÄTIGEN":
print("-")
else:
await interaction.response.send_message(f"{code_verify} \nSchreibe `Bestätigen` groß.", ephemeral=True)
try:
await interaction.user.kick(reason=',,Ich stimme den Regeln nicht zu ❌"')
except discord.Forbidden:
await interaction.response.send_message(f"I have not permissions.")
Ignoring exception in modal <extensions.Verify.cancel_modal object at 0x0000024FF340DDF0>:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 93, in callback
await interaction.user.kick(reason=',,Ich stimme den Regeln nicht zu ❌"')
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\member.py", line 679, in kick
await self.guild.kick(self, reason=reason)
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\guild.py", line 2733, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\http.py", line 353, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
await value.callback(interaction)
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 95, in callback
await interaction.response.send_message(f"I have not permissions.")
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\interactions.py", line 588, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
a better way to handle this without sending a confirmation message if the action failed is to send the confirmation after the kick happens (if it was successful)
Is there a way to do error handling with a modal?
yes, override on_error method
though what youre doing is also fine too so it isnt necessary
So? ```Py
@cancel_modal.on_error
async def cancel_modal_error(self, ctx, error):
if isinstance(error, Forbidden):
await ctx.send(f"Ich habe keine Rechte")
how then?
if youre subclassing the modal then by simply making a method named on_error
or by overriding that same attribute with the desired async function
this isnt hard to grasp
I think soo..
I did, didn't I?
uninstall it and all libraries that require discord.py
what you posted is not a class
is a modal
post the modal class
class cancel_modal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="🛑› Gebe diesen Code ein: Bestätigen (⏫ Groß)",
placeholder="📛 Achtung: BESTÄTIGEN = Rauswurf",
required=False, min_length=10, max_length=10))
async def callback(self, interaction: discord.Interaction):
if self.children[0].value == "BESTÄTIGEN":
print("-")
else:
await interaction.response.send_message(f"{code_verify} \nSchreibe `Bestätigen` groß.", ephemeral=True)
try:
await interaction.user.kick(reason=',,Ich stimme den Regeln nicht zu ❌"')
except discord.Forbidden:
await interaction.response.send_message(f"I have not permissions.")
copy paste your callback function and rename it to on_error
And then where should I write this?
In this class
class verify(commands.Cog):
def __init__(self, bot):
self.bot = bot
in the modal class
this is the modal class?
yes, make a new async method in there named on_error
it takes an error and the interaction
So?
what?
So or what?
okay
why are you going through the trouble to make this error handler in the first place when your try-except block works just fine?
i guess but now you want to send the confirmation message only if the condition isnt true?
So when i start the bot then come a error..
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\cog.py", line 711, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 159, in <module>
class verify(commands.Cog):
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 181, in verify
async def cancel_modal_error(self, ctx, error):
TypeError: on_error() missing 2 required positional arguments: 'error' and 'interaction'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\main.py", line 14, in <module>
bot.load_extension(f"extensions.{filename[:-3]}")
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\cog.py", line 783, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\cog.py", line 714, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'extensions.Verify' raised an error: TypeError: on_error() missing 2 required positional arguments: 'error' and 'interaction'
thats the leftover stuff
oh yeah
it also shows that you apparently can use it as a decorator
but theres no sensible point in doing it anyway when you can just make it in the class in the first place
Thank you, its working
But not..
Task exception was never retrieved
future: <Task finished name='Task-25' coro=<ModalStore.dispatch() done, defined at C:\Users\Amarz\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\ui\modal.py:200> exception=InteractionResponded('This interaction has already been responded to before')>
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
await value.callback(interaction)
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 103, in callback
await interaction.user.kick(reason=',,Ich stimme den Regeln nicht zu ❌"')
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\member.py", line 679, in kick
await self.guild.kick(self, reason=reason)
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\guild.py", line 2733, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\http.py", line 353, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\ui\modal.py", line 220, in dispatch
return await value.on_error(e, interaction)
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\extensions\Verify.py", line 89, in on_error
await interaction.response.send_message(f"I have not permissions")
File "C:\Users\zReaxrYT\PycharmProjects\Discord Bots\venv\lib\site-packages\discord\interactions.py", line 588, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
an error is occurring and the error handler uses the response object to send a message
you need to add a check in there to use the response object or the followup webhook depending on if the callback has already responded
this is really basic stuff
!install
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord beta:
pip uninstall discord.py
pip install py-cord==2.0.0b7
Install pycord alpha from git:
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
would it be py-cord==2.0.0rc1
Does py-cord have IPC in .ext
followup for what?
Like, does it actually work?
interaction.followup
yeah but for what?
like this?
well an error cant possibly occur before the first response so that works
this?
now there will definitely be an error no matter what
revert your changes back to this
what?
@slender lintel Hes telling you to change your current code back to this picture
Traceback (most recent call last):
File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/bot.py\", line 1068, in invoke
await ctx.command.invoke(ctx)
File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 174, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'
Ignoring exception in command play:
Traceback (most recent call last):
File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 165, in wrapped
ret = await coro(*args, **kwargs)
File \"/home/user_710339324889137184/main.py\", line 143, in play
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
File \"/usr/local/lib/python3.10/site-packages/nextcord/abc.py\", line 1707, in connect
raise TypeError(\"Type must meet VoiceProtocol abstract base class.\")
TypeError: Type must meet VoiceProtocol abstract base class.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/bot.py\", line 1068, in invoke
await ctx.command.invoke(ctx)
File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File \"/usr/local/lib/python3.10/site-packages/nextcord/ext/commands/core.py\", line 174, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Type must meet VoiceProtocol abstract base class.
@bot.slash_command(description="Play a song")
async def play(interaction: Interaction, channel: GuildChannel = SlashOption(channel_types=[ChannelType.voice], description="Voice Channel to Join"), search: str = SlashOption(description="Song Name")):
search = await wavelink.YouTubeTrack.search(query=search, return_first=True)
if not interaction.guild.voice_client:
vc: wavelink.Player = await channel.connect(cls=wavelink.Player)
elif not getattr(interaction.author.voice, "channel", None):
return await interaction.send("You must join a voice channel first.")
else:
vc: wavelink.Player = interaction.guild.voice_client
if vc.queue.is_empty and not vc.is_playing():
await vc.play(search)
await interaction.send(f'Playing `{search.title}`')
else:
await vc.queue.put_wait(search)
await interaction.send(f'Added `{search.title}` to the queue...')
vc.interaction = interaction
try:
if vc.loop: return
except Exception:
setattr(vc, "loop", False)```
@commands.command()
async def ping(ctx):
await ctx.respond('Pong!')
``` Why dosent my !ping work? (I have a bunch of slash commands that work fine, kick ban ect but normal commands just wont work)
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all(), debug_guilds=[965533467557371944,933803468815204372,964126154774679582, 740616442034258002], activity=discord.Activity(type=discord.ActivityType.watching, name='Over The Felbcord'))
Its been happening for a while, Its super annoying
It is because you are using @commands.command() instead of @bot.command()
You use @commands.command() when you're working on a cog.
Help please
Yes, I am working in a cog
still dosent work
you need to format the code
@commands.command()
async def ping(ctx):
await ctx.send('Pong!')```
^
could I just point something out?
send ss of your error bro.
nextcord yeah
i was trying a bot made in nextcord to see how it works
why would u ask here then?
then i will migrate its code to pycord 😂
I would have said if i had an error??
Ive got no error nothing
just dosent work, ive tried so many things
All the others are slash, I used slash as normal wouldnt work
man send t h e ss
from discord.commands import slash_command
from discord.ext.commands import Cog
from discord.ext import commands
class Pingg(Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self,ctx):
await ctx.send('Hey')
def setup(bot):
bot.add_cog(Pingg(bot))```
did you even load the cog
Yes
for filename in os.listdir('commandss'):
if filename.endswith('.py'):
bot.load_extension(F'commandss.{filename[:-3]}')
Its defo loaded, I cant see what else is causing itt
Anyone else know?
Hey guys, how can I hide my bot token for github repository?
Tyy
Hi, for the second day I can not solve the problem.
I use ORM sqlalchemy and postgres.
So I want to make as a photo, a mini shop using a database.
But there is a problem I can not do as in the photo, tried many ways not one of them is working properly.
I will be very grateful if someone has an example or a solution to the problem.(Oh exactly use pagination)
Ignoring exception in on_connect
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 380, in _run_event
await coro(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/bot.py", line 1042, in on_connect
await self.sync_commands()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/bot.py", line 631, in sync_commands
global_commands, method=method, force=force, delete_existing=delete_existing
NameError: name 'delete_existing' is not defined
Is it possible to have menus like this in modals using pycord? If yes, how? Found this on https://www.npmjs.com/package/discord-modals
Can someone help me?
Could someone help me? (I have been waiting 2h and i cant find anything to fix this, its been happening for a week)
use ctx.send(), not ctx.respond
I have now, still didnt fix
That was what i tried to fix it
from discord.commands import slash_command
from discord.ext.commands import Cog
from discord.ext import commands
class Pingg(Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self,ctx):
await ctx.send('Hey')
def setup(bot):
bot.add_cog(Pingg(bot))```
updated code
@snow citrus
do you have message intents?
^
can you not ping me pls
sorry, I am just getting annoyed since ive been trying to fix this for so long
again...
sorry switched off reply pings, i forgot xd
That hasnt pi nged u right
yes
alrigh, Please try help me when u can
Anyone able to help me? My command's wont work
Slash commands work fine
can you show your main bot file
oops
one sec
import os
from dotenv import load_dotenv
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all(), debug_guilds=[965533467557371944,933803468815204372,964126154774679582, 740616442034258002], activity=discord.Activity(type=discord.ActivityType.watching, name='Over The Felbcord'))
load_dotenv()
for filename in os.listdir('commandss'):
if filename.endswith('.py'):
bot.load_extension(F'commandss.{filename[:-3]}')
@bot.event
async def on_ready():
print('Connected to bot: {}'.format(bot.user.name))
@bot.event
async def on_application_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond(error)
else:
raise error
@bot.event
async def on_message(message):
if f"<@{bot.user.id}>" == message.content:
Welcome=discord.Embed(title="Felbot",url="https://github.com/VividBlue1/Felbcord-Py/tree/discord",description="Hello! I am a personal slave bot who helps around moderating and providing fun into the felbcord! \n If you have any questions about me feel free to ask @ignfoolish#0396 - my creator \n Join Felbcord here! \n
",color=discord.Color.blue())
Welcome.set_author(name="FelBot", url="https://github.com/VividBlue1/Felbcord-Py/tree/discord", icon_url="https://i.ibb.co/tz7VQJw/felb.jpg")
await message.channel.send(embed=Welcome)
bot.run(os.getenv("TOKEN"))```
you overwrote on_message
which is where commands are handled
you should add await bot.process_commands(message) to the end of that event
Does paginator have around the same length as a normal embed message or webhook?
in width size
uhhh the embed width is usually dependent on the embed itself
there isn't really an official method that normalizes it
async def on_message(message):
if f"<@{bot.user.id}>" == message.content:
Welcome=discord.Embed(title="Felbot",url="https://github.com/VividBlue1/Felbcord-Py/tree/discord",description="Hello! I am a personal slave bot who helps around moderating and providing fun into the felbcord! \n If you have any questions about me feel free to ask @ignfoolish#0396 - my creator \n Join Felbcord here! \n ",color=discord.Color.blue())
Welcome.set_author(name="FelBot", url="https://github.com/VividBlue1/Felbcord-Py/tree/discord", icon_url="https://i.ibb.co/tz7VQJw/felb.jpg")
await message.channel.send(embed=Welcome)
await bot.process_commands(message)```
I see, I'll experiment if stuff and see the max characters each can take
is that right
outside the if
?
... that's outside the entire function now
"outside the if" means the indentation should be inline with if
oh my bad
Okay done, Should my command work now?
probably
ill try it
Yay it works! Thanks so much
allgood
Is there a way to add all possible exception to a tasks so that my task loop doesnt stop 
I mean handle the exception inside a loop
well you could just try-except, or you can set a .error function with the decorator
Shit didnt know this exist
Thanks
allgood
note that this will override the default error print like the regular global error handlers, so i'd recommend having an else print at the end incase you get an error you haven't accounted for
I dont mind the error, i just wanna this loop keep run forever
Hi help me I need that when embed reaches the field limit it will make a new embed.
@market.command(name='products', description='View the list of products')
@cooldown(1, 15, BucketType.user)
async def products(self, ctx: discord.ApplicationContext):
embeds = []
for x in items:
paginator = pages.Paginator(pages=embeds, show_disabled=False, timeout=120)
await paginator.respond(ctx.interaction, ephemeral=False)
isee
Oh just reliased, The on message event no longer works
check len(embed.fields) at the start of the loop?
field limit is 25
Edit: It works but if theres a message along with the ping it wont work
whys that?
I have a file that is over 1000 lines long, any tips to organize it?
import os
from dotenv import load_dotenv
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all(), debug_guilds=[965533467557371944,933803468815204372,964126154774679582, 740616442034258002], activity=discord.Activity(type=discord.ActivityType.watching, name='Over The Felbcord'))
load_dotenv()
for filename in os.listdir('commandss'):
if filename.endswith('.py'):
bot.load_extension(F'commandss.{filename[:-3]}')
@bot.event
async def on_ready():
print('Connected to bot: {}'.format(bot.user.name))
@bot.event
async def on_application_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond(error)
else:
raise error
@bot.event
async def on_message(message):
if f"<@{bot.user.id}>" == message.content:
Welcome=discord.Embed(title="Felbot",url="https://github.com/VividBlue1/Felbcord-Py/tree/discord",description="Hello! I am a personal slave bot who helps around moderating and providing fun into the felbcord! \n If you have any questions about me feel free to ask @ignfoolish#0396 - my creator \n Join Felbcord here! \n ",color=discord.Color.blue())
Welcome.set_author(name="FelBot", url="https://github.com/VividBlue1/Felbcord-Py/tree/discord", icon_url="https://i.ibb.co/tz7VQJw/felb.jpg")
await message.channel.send(embed=Welcome)
await bot.process_commands(message)
bot.run(os.getenv("TOKEN"))```
You can use cogs if its full of commands events ect
^
wait so what's the issue
For example before it would work like this
@felbot Hi
@felbot
both would send the message now only the second one works
Yeah
you're checking if f"<@{bot.user.id}>" == message.content
which means it will work if the message ONLY contains the bot mention and nothing else
How would i allow it to have message content too?
you could do message.content.startswith(...) or ... in message.content
but if you do either of those, you should check if message.content exists at all
Hmm i guess we can do if bot.user in message.mention
Would
if in message.content = <@{bot.user.id}> work
other way round, the other solution dot proposed could be more appropriate
but both of these will trigger if the bot is mentioned anywhere in the message (not just the start) or even when someone replies to the bot
Thats fine for now, If i have issues i can change it
@bot.event
async def on_message(message):
if bot.user in message.mention:``` dosent work? am i missing something
message.mentions
allgood
Are bots able to check for mutual servers?
user.mutual_guilds
So i can get a list of users that are in 2 guilds the same?
oh no, mutual_guilds compares the user and the bot
Wym? (Would explaining what im trying to do help?)
probably yeah
So
I have a ratter server and a server i want to ban all the ratters from (for obvious reasons) So i want to find all the people who are in that server and get their names/ids so i can ban them, The best way we are using is to get mutual servers but i want to see if i can automate this
It isnt, Its only in the server i want to ban them from.. but since that wouldnt work is it possible to see the mutuals from my alt account
nope
(Btw obviously ima leave the server before its terminated)
the bot would have to be in the other server if you wanted to loop over the members or something
the best you can do is get a list of user IDs to have banned
(manually)
hey, i have a very strange problem
i define bot like this:
import discord
from discord.ext import commands
def get_prefix(bot, message):
return commands.when_mentioned_or("-")(bot, message)
bot = commands.Bot(
command_prefix = get_prefix,
strip_after_prefix = True
)
but it responds only when i type "<bot_ping> help" and completely ignores "-help", there are even nothing in the terminal
by the way, bot doesn't ignore a message - get_prefix invokes
something really strange...
(using py-cord 2.0.0rc1)
Would it be possible to get all the ID's of members to ban them without my bot being in the server
add to the commands.Bot "help_command=None"
this happens with every command, not only help
try it with
def get_prefix(client, message):
with open("File.json", "r") as f:
prefix = json.load(f)
return prefix[str(message.guild.id)]
ok, i've set
with prefix does nothing
with ping raises commandnotfound exception
or just like prefix.get(str(messae.guild.id), '!')
so you can fall back on a default prefix
firstly i was fetching the prefix from database, same result
then i simplified the way im getting it for test... nothing
do you have Intents?
wait a minute..
"message content intent" turned on
what is wrong with it?
does your string start and end with an "?
Is that a f-string?
send screenshot with more code pls
Is it possible to make a command that can ban up to 500 user ids at once? (without crashing the bot xD)
I don't think so...
What about 250?
use ' instaed of "
And why would you want that xD
that works
I need to mass ban some users who are ratting servers (Specficly minecraft skyblock discord servers)
they do discord tokens too ect
Try it. Only way is using await and ban_member or so. But I don't know if there's an api limit for that
use a for loop...
@slash_command(name="ban", description="Bans a member")
async def ban(self, ctx, member: discord.Member,*,reason):
if ctx.author.guild_permissions.moderate_members:
await member.ban()
await member.send(reason)
await ctx.respond(f'{member} has been banned from felbcord', ephemeral=True)
else:
await ctx.respond('You do not have the correct permissions for this',ephemeral=True)``` what do i add to this
You would need to be able to specify multiple users in the command but I actually don't know how you would do that. But say you got multiple members as a list you could do:
for member in member_list:
await member.ban()
await member.send(reason)
...
alr
you should first send the message to the member and then ban him
Whys that needed?
(ofc in an actual bot yes but for this, why?)
I mean for a actual bot
yeah
@crimson coral Hey sorry for ping, I am confused how would i make a ban command to ban multiple ids at once?
Like 100?
573*
Looping through a list of ids?
Yeah, but how i havent done it before
?
I need to edit my ban command to ban multiple user ids at one time
instead of one member at once
@slash_command(name="ban", description="Bans a member")
async def ban(self, ctx, member: discord.Member,*,reason):
if ctx.author.guild_permissions.moderate_members:
await member.ban()
await member.send(reason)
await ctx.respond(f'{member} has been banned from felbcord', ephemeral=True)
else:
await ctx.respond('You do not have the correct permissions for this',ephemeral=True)```
or ban all ids in a text document
one or the other
explanation is here
literally spoon fed
lol
yes mate but i have said, I dont understand it
which part? the looping over a list?
Do you know what a for-loop is used for?
To repeat a command/event/code?
I think the main problem for you is how you can get the ids of only the 573 users you want to ban...
A freind managed to do it in c# (dont ask why its c# LMAO)
well then ask him and convert it to python...
he dosent know python
but you do.
allow input formats such as text files
He cant convert it to python if he dosent know it? i dont know c#
you should be able to deduce the loop structure from c# into python
yes.
Most programming languages share a kind of similar syntax. You can find everywhere basics like for/foreach, if, while and so on. So it shouldn't be that difficult to try understand what he did in c# and deduce it to python. Provided that you know the python basics ofc...
how can I make "wait_for" for both message or button at the same time?
hmm okay, I'll search for another way
what exactly are you trying to do?
check whether user clicks button or sends a message
but wait I had the solution somewhere in my previous bot
oh yea, here it is
done, pending = await asyncio.wait([
client.wait_for('message', timeout=1200, check=check_input),
client.wait_for('reaction_add', timeout=1200, check=choose_setting)
], return_when=asyncio.FIRST_COMPLETED)
try:
stuff = done.pop().result()```just need to change reaction into button
fair enough
When adding drop down menus in the modal, would you class the drop down menus itself and then add it via the Modal Class
or add the drop down menu in the modal class
Does pycord support pop ups
what?
That is a Modal
Is there a doc on it
Learn how you can implement Modals in your Discord Bot with Pycord!
Ty
wait what... :(
yeah....
yes, some already support stuff like that
modals only support text right now
So I have been fixing something that's not even implemented well that's great
discord hasn't really done anything else with them yet
idk if I saw a different language implementing them but they've implemented the drop downs in modals
^
huh
is there any screenshots of this? can't find anything on it
though i haven't been active recently so maybe i completely missed it
I'll try to find it, though chances are very low since I didn't click on the video just the the thumbnail and a bit of the title saying menus in modals
unless the video was clickbait well damn then
hmmm so it does
how do you edit a ephemeral message from interaction?
is there a way you get around the text limit in embeds
have 2 embeds
can it be done in 1 embed?
Not if you already reached your limit
can you try ##1419, should work
(he says as one of the tests fails, nice)
...forgot to import union
end me, should work now
Hello, how can you make it send a message as soon as you reply to the bot?
wdym by this. Replying like saying an answer after the bot asks a question? or just when someone uses the reply feature like I am doing rn
So if I reply to you like I'm doing right now, the bot should send a message as soon as you reply to the bot
I think you can do an on_message event to get the message. Then check if the type of the message is an instance of discord.MessageType.reply. Then get the messagereference which has a message id. Then fetch the message to see if the message was sent by the client.
im not exactly sure how message.reference actually works
but here is the docs fo rit
Thanks
Can two buttons have the same custom ID?
nope
scheisse
?
I have a command that a user can call that i want to create a custom view
however that means i need a custom id for each button on each message called by the command
why do you need the custom id
because buttons need custom ids to make a persistent view
the view is created after a modal is submitted
and my approach is to add the view to the bot at that point with the message id
Tbh i could make the button ID a random 100 digit integer
which means the chance of two buttons conflicting is 1/10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000
or something
however, you can make a 100 character long string\
exactly
custom ids have to be strings anyways
yes, but there is probably a char limit
of 100 chars
or even better
i could just make a random 100 character long string for every message
uhh I was thinking just put the custom id the message id
that was my original approach
however
you can't pass self into a decorator
so i dont think i can do it without using a global
if custom_id is not None and len(str(custom_id)) > 100:
raise ValueError("custom_id must be 100 characters or fewer")```
indeed it is 100
do you need a constructor?
Yes
async def callback(self, interaction: discord.Interaction): # TODO: Add ability to edit claims
# name = self.children[0]
# lore = self.children[1]
## for countries:
# head of state = self.children[2]
# flag = self.children[3]
# claim = self.children[4]
## for organizations:
# leader = self.children[2]
# motivation = self.children[3]
# emblem/flag = self.children[4]
## for others:
# entity = self.children[2]
# other info = self.children[3]
# image = self.children[4]
embed = children_to_embed(self.children, self.entity, interaction.user)
approval_channel_id = io.load_approve_channel(interaction.guild_id)
approval_channel = await interaction.guild.fetch_channel(approval_channel_id)
claim_msg = await approval_channel.send(embed=embed)
approval_view = views.CountryApprovalView(interaction.user, self, embed, claim_msg)
bot.add_view(views.CountryApprovalView(), approval_view.claim_msg.id)
await interaction.response.send_message(f"Claim successfully added! An admin will approve you in <#{approval_channel_id}>.", ephemeral=True)
approval_view.orig_msg = await interaction.original_message()
await approval_view.wait()
this is the callback of the modal that creates the view that i want to be persistent
class CountryApprovalView(discord.ui.View):
"""A view attached to country approval messages which adds an approve and deny button to the message."""
def __init__(self, user: discord.User, claimmodal, embed, claim_msg):
super().__init__(timeout=None)
self._claimant = user
self._claimmodal = claimmodal
self._embed = embed
self._claim_msg = claim_msg
self.orig_msg = None # the original /claim message
@discord.ui.button(label="Approve", style=discord.ButtonStyle.green, custom_id=f"Custom ID")
async def approve_button_callback(self, button: discord.Button, interaction: discord.Interaction):
if interaction.user.guild_permissions.administrator:
await interaction.response.send_message("Successfully approved claim!", ephemeral=True)
button.label = "Approved"
button.disabled = True
self.children = [button]
self._embed.color=discord.Color.green()
await self._claim_msg.edit(f"<@{interaction.user.id}> has approved this claim!", view=self, embed=self._embed)
await self.orig_msg.channel.send(f"<@{self._claimant.id}>, your claim \"{self._embed.title}\" has been approved by {interaction.user.name}!")
self.stop()
io.register_country()
else:
await interaction.response.send_message(f"You do not have permission to approve claims!", ephemeral=True)
... more buttons ...
this is the view itself
i am importing bot from main in modals.py (the file containing the modals) and calling bot.add_view() in the modal callback
and i dont know if that would work
wouldnt they gonna have a different scope?
i don't think so? but i dont know
bot is declared globally in main.py
import os, discord, config
import countrybot.io as io
from countrybot.views import CountryApprovalView
from dotenv import load_dotenv
initial_extensions = ['countrybot.cogs.date', 'countrybot.cogs.errorhandler', 'countrybot.cogs.country']
intents = discord.Intents.default()
intents.message_content = True
load_dotenv()
bot = discord.Bot()
.
.
.
i dont really know if it would work though
but i also dont know if putting self.add_view() in on_ready would work if the message with the view is created after the view is added as persistent
if i make a random 100 character long string of any printable ascii character, the chance of two strings colliding is (1/95)^100
so i think that a collision is unlikely between button ids lmao
ok
my thought is saving the message id as button id or get current timestamp, and save the id to a json, therefore in on_ready event you can recreate the view or button and set them as persview again
ye with timestamp you can never get the same int
but all four buttons are initialized at the same time
well
relatively the same time
well have them 1 prefix or suffix then
oh thats true
when doing bot.add_view(persistentview()) are you adding the specific view that is initialized by that call to persistentview() as a persistent view? Or are you adding any view of type persistentview as a persistent view?
im going to do this
HOWEVER
i have no way of saving the view
if i could pickle it that would be awesome but:
a) i dont think views are pickleable
b) even if they were, i cant save the view because it contains user inputted data, and unserializing user inputted data is a security risk
my brain is too pepeg to understand what youre saying, excuse me?
ignore that
ok nevermind
persistentview() creates a specific instance of a view
and every time a view is added to a message, it's a different instance of that view
so when you do bot.add_view(persistentview()), i think what it does is it adds that specific instance of the view to every message that needs to have that view
i think
and the issue is that i can't have one instance of the view attached to every message with the view
each message needs a different view instance
so they all have to be added as separate views
I THINK
i am not sure though
this is what i have gathered from the info i have seen
but my understanding could be entirely wrong
my idea is that maybe i can save the view instance as a json file and store that in the database my bot is using
however if the bot goes offline and online again, and that view instance is added to the bot from the json file, i don't know if the view will still work
You can set the message where this view is belong to, by passing the message id
And yeah ig you can use json, create a unique id and use the unique id as key with value containing your message id, data inputted by user, etc.
I dont know if it will work though
I havent tried aswell, why no tias
why no tias?
Try it and see
ahh
i am going to
TypeError: Object of type CountryApprovalView is not JSON serializable
Thought so
sadge
it straight up might not be possible to make this view persistent
You dont pass the view instance
But any data inside that view
Like button id etc.
Then on on_ready event, you iterate the saved json, recreate the class then pass the data where it belongs
But that view is being view.wait()ed by the modal callback
i dont know if the class can be destroyed and recreated
the code here is kinda complex
-original slash command sends message with dropdown view
-each option in the dropdown view sends a modal specific to that option
-submitting the modal sends a message to another channel with the approval view
-one button edits the embed that the view is attached to, another deletes the message, another sends a modal to the user, and each button edits the approval view itself
-when the approve or deny buttons are pressed, a message is sent to the user in the channel that the original slash command was used in
After much pain and hours of coding everything works but the view is not persistent
so if that message with the view awaiting a button press is sent and the bot goes offline then online again the buttons stop working
so it's not essential
especially considering that the messages, in theory, shouldn't wait too long to be approved or denied
but it's a quality of life thing
and honestly i dont know if a persistent view can be added heer
here*
or rather
i don't think i am skilled enough to implement it
how can i set the default target user of an option to the author itself
b!rtfm option
I couldn't find a documentation with the name option! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake
b!rtfm pyc option
PS C:\Users\Fammy\Desktop\keni> & C:/Users/Fammy/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Fammy/Desktop/keni/bot.py
Traceback (most recent call last):
File "c:\Users\Fammy\Desktop\keni\bot.py", line 13, in <module>
bot = commands.Bot(command_prefix='.' , case_insensitive=True ,intents=discord.Intents.all())
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'
PS C:\Users\Fammy\Desktop\keni> ```
didnt tell me anything
b!rtfm pyc choice
b!rtfm pyc option
I dont think you can in the slash command
you could code it to target user if they dont select a value and it usually shows the by default on list
Traceback (most recent call last):
File "c:\Users\Fammy\Desktop\keni\bot.py", line 13, in <module>
bot = commands.Bot(command_prefix='.' , case_insensitive=True ,intents=discord.Intents.all())
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'
PS C:\Users\Fammy\Desktop\keni>
Anyone help i reset my pc few days ago and now its not working
My code is not importing pycord
let me try if default = ctx.author will work lol
sure?
do pip list
1 min
also do
1 -> pip uninstall py-cord
2 -> pip install py-cord==2.0.0rc1
3 - > try code again
4 - > if it fails then change "commands.Bot" to discord.Bot or discord.ext.commands.Bot()
in vc code its white insteal of green
other modules are in green but discord one is in white
mhm try to reinstall ig
omki
also pip is not working i have to do py -m pip
C:\Users\Fammy>pip list
'pip' is not recognized as an internal or external command,
operable program or batch file.```
does creating child classes of persistantview not work?
how would that solve the problem?
is there a method to get webhook object by its ID?
Thanks!
Is it possible to create a paginator during an on_message event?
Can I use tasks to auto start my bot if it dcs
sures?
Is that what their meant for or what's it most commonly used for
Concept
With the tasks extension, you can make background tasks without worrying about the asyncio hell and mind bogglers like "what if my internet dies" and "how do I handle reconnecting" with the added benefit of a lot of useful additions that are one line of code away!
Yeah so would I put my bot run in tbe task
The
i havent experimented with tasks really
Alr
does anyone know how to make buttons from a view work even if i restart the bot?
https://docs.pycord.dev/en/master/api.html?highlight=add_view#discord.Bot.add_view add a view to the bot with bot.add_view(view, msg_id)
alr ill try
still same problem
not really scince you need the callback
You can create a class for the view and use a decorator to add a button but else I think no
a bit complicated, but I can try to explain
do you have subclassed view or automatically created?
imma wait until it gets released since I have no idea how to implement from ##1419 to the file
How can i pass field im embed? i mean, like make space in name
I'm confused what you're asking for but you add a field using embed.add_field(name="name with space",value="val")
can you field in a embed with nothing in it
right
You need to set the name to a zero width space iirc
You will need to look up the unicode for it
How to get the message ID of the message the bot sent through a webhook?
fair enough, discord doesn't fully support it either (broken on mobile, some crashes) so yeah better off waiting
does pycord still get .news in a channel because while looping through guild.channels it says Error: 'TextChannel' object has no attribute 'news' so I'm thinking they haven't changed that to is_news()?
what version are you on? that's fixed in rc1
im on rc1
huh
oh wait im wrong
not sure how to fix this
is it fixed in alpha?
not rc1, i made a pull for it but it'll be next version ##1370
yeah
sad sad dude
I'm making a dashboard
and I'm doing welcoming for it sooo yeah
idk how to do it efficiently so im gonna just do it the bad way
(cuz i am bad)
if you don't want to install the entire alpha branch, you can just go through the code changes and apply that
it's like 3 lines
just add this right? py @property def news(self) -> bool: return self.is_news()
yeah
in the textchannel class alr
since you're using the decorator, the callback needs to include the select argument
i.e. def callback(self, select, interaction...)
idk where that file is located though, I don't remember I knew before though
I have it python from windows store btw
oh wait dw
i got it
if you're using an ide like vscode or pycharm you can control+click the module
yeah
IPC route returned values which are not able to be sent over sockets. If you are trying to send a object, please only send the data you need. whoops, how do I send the id and the name and then use it in html?
I tried using dicts, though that just messed everything up.
Hey, how can my bot find suspicious users?
depends on your criteria
class Setup(commands.Cog):
def __init__(self, client:commands.Bot):
self.client = client
self.all_user_ids = [user.id for user in client.users]
self.ping()
def ping(self):
for guild in self.client.guilds:
for member in guild.members:
print(member.id)
Console Output -
$ C:/Python/python.exe "e:/Python/Evelynn Workspace/Evelynn6/main.py"
Logged in as Reii#2207
Why do i not get any output? I have all intents enabled. when i print self.all_user_ids i get []
Does anyone know how to track the inviter if someone joins the server?
Using the on_member_join event?
not provided by the api
How does invite tracker bot manage it 
magic
self.client.guilds is empty, you're probably running it before on_ready is fired
i see, i am running it before on_ready. its in a cog
so ig i should use a cog listener
they probably check every invite's usage count, and guess by checking which one has changed
yeah just do it in a cog on_ready listener
works now. Thanks!
allgood
it maintains a constantly updating list of the number of uses on invites
when a member joins, it checks which invite changed
and then determines which invite was used
https://docs.pycord.dev/en/master/api.html#discord.Invite
https://docs.pycord.dev/en/master/api.html#discord.Guild.invites
check these two
atleast thats my best guess
pretty much
Will try
Guys you have any idea on how to create application bot?
Like
Should I play around with for loops?
What's yoru idea
*your
maybe you want modals?
json is fine on a small scale, but ideally you'd use a database
Like MongoDB?
yeah
I like using json it's nais
fair enough
mongo is best imo
easy to use
easily scalable
the pymongo library is well written
works as a simple database but when you need relational models then you need to ditch mongodb for something that uses sql
ye
in my experience i havent needed sql so far
hopefully it stays that way
cause i hate sql
for one of my projects im just using sqlite since its the most convenient
sql isnt that intidimating when you learn the basic syntax
sqlite3 is just not for me since i cant open the .db file and read it like i would with a .json
lmao
ik the syntaxes quite well, had them for my recent comp sci test
do be weary when youre using json files as databases
theyre not designed to be such
i use mongoDB lol
How can i have seperate settings for a feature per guild? (For example i have a prefix command, how would i have that per guild)
and have per guild permissions ect
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'Embed' object is not iterable
Not sure how to solve the problem?
you would have to have a separate database
that stores all these settings
for example a json file (not recommended, user MongoDB instead)
So the database can store per server data?
Full traceback?
So, MongoDB works with pycord right?
Traceback (most recent call last):
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 122, in wrapped
ret = await coro(arg)
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 825, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\modules\pages.py", line 57, in pagetest_new
await paginator.respond(ctx.interaction, ephemeral=False)
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\ext\pages\pagination.py", line 909, in respond
msg = await interaction.response.send_message(
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\interactions.py", line 603, in send_message
payload["embeds"] = [e.to_dict() for e in embeds]
TypeError: 'Embed' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\bot.py", line 1098, in invoke_application_command
await ctx.command.invoke(ctx)
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 331, in invoke
await injected(ctx)
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 122, in wrapped
ret = await coro(arg)
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 1091, in _invoke
await command.invoke(ctx)
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 331, in invoke
await injected(ctx)
File "c:\Users\artyr\Desktop\bot_work\Discord\AmoBot_public\env\lib\site-packages\discord\commands\core.py", line 128, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'Embed' object is not iterable
Because i have only ever heard of it with js
theres no link bw the two. they are both standalone libraries/dbms
theres pymongo
yt it, theres some nice tutorials
np
ty
np
Bump
pass in discord.Thread
if only that worked.
what does it do instead?
gives me nothing
hmmm hold on
Why embed is not sent with embed.field?
probably because your pages_list is empty.
...you're doing embed.clear_fields()
how best to do it?
remove that line.
how can a make a per guild prefix?
or move it above the for i in pages_list
