#discord-bots
1 messages · Page 150 of 1
10s
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
error: File "main.py", line 161
if round_length < 36:
^
IndentationError: unindent does not match any outer indentation level code :https://paste.pythondiscord.com/xeqilegagu
you missed a colon above that line
holy smokes
ye but then look at this
that is a really unnecessary if/elif chain
error:File "main.py", line 160
round_id = str(round_id):
^
SyntaxError: invalid syntax
code: https://paste.pythondiscord.com/ipotonetid
Remove the :
do you think this is correct?
wich one?
you didn't close the bracket + no colon
the bracket is closed now
look this is the error:File "main.py", line 160
round_id = str(round_id):
^
SyntaxError: invalid syntax
code: https://paste.pythondiscord.com/ipotonetid
new pastebin
@commands.has_permissions(administrator=True)
async def purge(ctx, limit: int):
await ctx.channel.purge(limit=limit)
await ctx.send('Cleared by {}}'.format(ctx.author), delete_after=10)
await ctx.message.delete()
@purge.error
async def clear_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You can't do that!", delete_after=10)``` it dosent send the message `Cleared by .......` and `You can't do that!` after i added delete_after
this is wrong too
I want a system where I generate a key that the user will enter to verify his purchase and identify him to a pc hwid
how do i fix it then?
?
move that round_id
It probably did but you immediately delete the message after that
place it with other parameters in above line
Wait, I misread a bit
ah, that's a bit more complicated and I don't think this is the right place to be asking :p
like this?
got any idea how to fix?
round_id = str(round_id):
async def mines(interaction: discord.Interaction, tile_amt: int,):
Where to ask then ?
#1035199133436354600 perhaps
and if i type 2 messages and type !clear 2 it will delete only one because the message !clear 2 counts in the clear
🗿
and idk how to fix it
cna u show me?
Then delete the ctx.message before calling purge
do you know functions?
no.
kk thx
cna u show what the code look first?
would it?
yes
Where can I ignore this error if the bot does not have access to this channel?
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 221, in on_message
c = await bot.fetch_channel(int(servers['global_id']))
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 1729, in fetch_channel
data = await self.http.get_channel(channel_id)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\http.py", line 391, in request
raise Forbidden(response, data)
nextcord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Check the bot's permission or handle the error

!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
#bot-commands
help error is : File "main.py", line 492
scraper = s.create_scraper()
^
IndentationError: unindent does not match any outer indentation level code: https://paste.pythondiscord.com/tubewuqase
like this?
How to handle this error
catgal
You can use @command_callback.error decorator to register error handler to a function
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
catgal
@client.tree.command(name='user_info', description='gives you the info on the user you')
async def userinfo(interaction: discord.Interaction, member:discord.Member=None):
if member==None:
member = interaction.user
roles = [role for role in member.roles]
embed=discord.Embed(title=f'{member.name}#{member.discriminator}', description=member.mention, color=0x1eca37, timestamp = datetime.utcnow())
embed.set_thumbnail(url=member.avatar)
embed.add_field(name="__Registered__", value = member.created_at.strftime('%d/%m/%Y, %H:%M:%S'))
embed.add_field(name="__Joined__", value = member.joined_at.strftime('%d/%m/%Y, %H:%M:%S'))
embed.add_field(name='__Status__', value=member.status)
embed.add_field(name="__ID__", value = member.id)
embed.add_field(name=f'__Roles ({len(roles)-1} Roles)__', value=' '.join([role.mention for role in roles[1:]]))
embed.set_footer(text='Created by UniqueDolphin#8001')
await interaction.response.send_message(embed=embed)
When i am trying to tag a member it doesn't work
discord.app_commands.errors.CommandInvokeError: Command 'user_info' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.fields.4.value: This field is required
This is the error
Field value is required
I am a new developer can you tell me how to fix this?
bot.run(“token”)
If you have that at the end of your code then it means you have an error in your code
Token being your bots token
You need to provide the Field Value
You set discord.Member = None
so how do i fix this?
what should i put there
Remove the = None?
I dont really know what its doing
Hes setting it so that member is always None
discord.Member=None
No matter what anyone puts in there it will equal None
No?
member: discord.Member=None):
i think they are talking about
async def userinfo(interaction: discord.Interaction, member:discord.Member=None):
Hes setting discord.Member to none here no?
I know
But hes setting it to always be none so his code will have issues later
Is it?
Didnt know it was a kwarg
@fallow jolt it is still giving me an error when i am trying to tag someone
discord.app_commands.errors.CommandInvokeError: Command 'user_info' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.fields.4.value: This field is required
This error
Issue with the embed
hi i got this code
but i want the bot to specify how much messages it deleted
so Cleared MESSAGES by {ctx.author}
any1 knows how
What error you get
you probably shouldn't just copy and paste code lol. but ill give u a hint, limit
need full error
What
whats line 1
Show your code
import i assume
yeah probably
@frosty umbrawhen using this the output of the status is always offline.
i dont think u have sum modules installed
yea pretty sure he is doing some sketch shit. the bot is named fake sniper
Ok dm me it
Ill check
yeah
@frosty umbra
then the member is offline lol
Hes doing sketchy stuff
What do you mean
@client.tree.command(name='user_info', description='gives you the info on the user you')
async def userinfo(interaction: discord.Interaction, member:discord.Member=None):
if member==None:
member = interaction.user
roles = [role for role in member.roles]
embed=discord.Embed(title=f'{member.name}#{member.discriminator}', description=member.mention, color=0x1eca37, timestamp = datetime.utcnow())
embed.set_thumbnail(url=member.avatar)
embed.add_field(name="__Registered__", value = member.created_at.strftime('%d/%m/%Y, %H:%M:%S'))
embed.add_field(name="__Joined__", value = member.joined_at.strftime('%d/%m/%Y, %H:%M:%S'))
embed.add_field(name='__Status__', value=member.status)
embed.add_field(name="__ID__", value = member.id)
embed.add_field(name=f'__Roles ({len(roles)-1} Roles)__', value=' '.join([role.mention for role in roles[1:]]))
embed.set_footer(text='Created by UniqueDolphin#8001')
await interaction.response.send_message(embed=embed)
Restart your bot and wait a bit
the output of status is always offline
im pretty sure u need intents for that do u not
What intents you got enabled
maybe not.
You do
Just checked
Intents.members should be enabled
what?
Oh its presence true
Its a special intent so you have to enable it on your bot and in your code
lmfaooooo
From 10 year olds
thats why its called fake sniper
Hes asking me why I cant just help him
I have the source to the program and sure enough it sends cookie to webhook and checks what items they have
smh
If they have good items he’ll probably use it to steal from the kids
Also his code looks like its been stolen from someone elses github
He's ban ?
He gave me his webhook too 💀
lololol.
Server in his bio is a blackmarket server for rolbox
@bot.event
async def on_message(message: nextcord.Message):
if message.author.id == bot.user.id:
return
else:
_public_global_chat_check = await bot.settings.get_all({}, projections=Projection(Show("global_id")).build())
if _public_global_chat_check is None:
return
if _public_global_chat_check is not None:
_server_gl_cc_dict = {"_id": message.guild.id}
_server_gl_cc = await bot.settings.find(_server_gl_cc_dict)
if _server_gl_cc is None:
return
if _server_gl_cc is not None:
if message.channel.id == _server_gl_cc["global_id"]:
for servers in _public_global_chat_check:
print(servers)
if "global_id" in servers:
c = await bot.fetch_channel(int(servers['global_id']))
try:
await c.send(message.content)
except nextcord.Forbidden:
continue
else:
continue
return()
else:
return
return```
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 221, in on_message
c = await bot.fetch_channel(int(servers['global_id']))
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 1729, in fetch_channel
data = await self.http.get_channel(channel_id)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\http.py", line 391, in request
raise Forbidden(response, data)
nextcord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
how can i keep the loop running even if he doesn't have access to this channel
bot.fetch_channel is causing the error, not c.send. You shouldn't be fetching channels either, and you don't call return
It won't error but it'll return an empty tuple
code doesn't match error
is there a way by one can limit as to how much a bot has ran?
for example i have a bot abc which sends counting 0-150 now i want the bot to stop when it hits 150 and never run for 24 hours after that it will start from 0 again
i mean you can stop the bot once its hits the count limit but starting it back up wont have anything to do with the bot itself
that'll be done manually
no i meant i can stop the bot when it hits 150 the problem is, if someone tries to start the bot again it should show an error
thats what i wish to do
something like sorry you hit 150 etc etc
you cant do that lmao
how are u gonna show an error if the bot isnt even running
He’d have to save a bunch of data to do it
ye
he still can't he stopped the bot lmao
o okayokay
yea lmao
okay
Just quit the bot after 150 and then restart it in 24 hours
or just "disable" the counting function so you can still respond with the bot if someone tries to "start" it again
okok
also is there a way i can write something to a file when i manually close the program by pressimg the cross button
There is no different between manually closing and closing with a script a think
Unless you go binary level LOL
really?
You could try to detect if the mouse is hovering over the cross button
But that would be difficult
damn okay
You could make a command to start the counting and leave it running 24/7
And make it have a cooldown of 24 hours
And make it so only you can run it
and how can I make it continue despite the error?
import os
client = discord.Client(intents=discord.Intents.all())
@client.event
async def on_ready():
print('Bot is online, as {0,user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$Hello"):
await message.channel.send("Hello!")
client.run(os.getenv("token"))
File "main.py", line 21, in <module>
client.run(os.getenv("token"))
File "/home/runner/WoefulOutrageousProjections/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/runner/WoefulOutrageousProjections/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "/home/runner/WoefulOutrageousProjections/venv/lib/python3.8/site-packages/discord/client.py", line 745, in start
await self.login(token)
File "/home/runner/WoefulOutrageousProjections/venv/lib/python3.8/site-packages/discord/client.py", line 577, in login
raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')
TypeError: expected token to be a str, received NoneType instead
```
This is the error i get
i think i found a way, what i can do is first of all making my code exit by keyboardintterupt
catch the keyboard intterupt and write the value of counting in a file
then when the bot is restarted use that value and update it again on exit
can you make a bot stream in vide channels
await ctx.response.send_message((embed=em), ephemeral = False)
``` i get syntax error on the embed=em part
why does this happen?
What is this
I mean what library
Oj dpu
embed=em without the ()
Oh lol
@client.event
async def on_message(message):
if message.author.client:
return
File "/home/runner/level-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 32, in on_message
if message.author.client:
AttributeError: 'Member' object has no attribute 'client'``` help pls
Define message
its bot
message.author refers to member, user
and member.bot is the bot.
so its message.author.bot
membe🤔
can evaluate to an instance of Member | User*
yeaa i dont they even understand what we are talking ab anyways. member.client
lol
nobody reads docs anymroe
Guess i dont exist😔
they copy pasted some code had ```py
if member.bot:
and then change all `bot`s to `client` 😂
probably lmfao
Yeah Thank you. I fixed it all now
from discord.ext import commands
from datetime import datetime, timedelta, timezone
bot = commands.Bot(command_prefix='!')
@bot.command()
async def time(ctx, country: str):
# Set the timezone for the country
if country.lower() == 'usa':
tz = timezone.utc
elif country.lower() == 'japan':
tz = timezone(timedelta(hours=9))
else:
# If the country is not USA or Japan, use UTC as the default timezone
tz = timezone.utc
# Get the current time in the specified timezone
now = datetime.now(tz)
current_time = now.strftime('%H:%M:%S')
# Send the current time to the user
await ctx.send(f'The current time in {country} is {current_time}')
bot.run('Token')```
really simple idk why its not working
is there any way to pause invites through a bot? I'm using nextcord btw
no errors just nothing happens
yes. using guild.edit
alright, thanks!
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., region=..., afk_channel=..., owner=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have the [`manage_guild`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Permissions.manage_guild "nextcord.Permissions.manage_guild") permission to edit the guild.
Changed in version 1.4: The `rules_channel` and `public_updates_channel` keyword-only parameters were added.
Changed in version 2.0: The `discovery_splash` and `community` keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned...
unfortunate. but in dpy and disnake. its guild.edit(invites_disabled=Bool)
it doesn't exist in nextcord. kind of cringe
Hm its still not there
why tho. it was added almost 3 months ago now
i think thats cuz they are focused on the rewrite rn 🤺, and the feature isn't forsure unnoticed by the devs because they added it in Guild featues
yep
ill just annoy the owner until they add it
!d discord.Guild.features
A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.
They are currently as follows:
Seeing the word "re-write" has given me flashbacks to Rin
I think I've rewritten at least 4 times
they plan on* completing the rewrite 👀
is that the case for you?
I have commitment issues
😏 commit all at once then
unless i torture you into doing it
I might actually re-write
You got me feeling that kind of way sarth
I'm gonna look like an idiot when 5 hours pass and I give up already
well take your time 🤺 takes another year
Was your wrapper a mix of Rin and something else
It looks oddly familiar 👁️ 👁️
it uses event functions declaration similar to rin!
@as_listener(wyvern.Events.EVENT_NAME)
and the naming convention is same as hikari -tanjun but thats it
no wait wtf rin has listeners too
https://github.com/sarthhh/wyvern/blob/master/wyvern/events.py
but its just the saMe class name ig
from __future__ import annotations
import asyncio
import os
from datetime import timedelta
import rin
token: str = os.environ["DISCORD_TOKEN"]
intents = rin.IntentsBuilder.default(guild_members=True)
client = rin.GatewayClient(token, intents=intents)
@client.once(rin.Events.READY)
async def ready(user: rin.User) -> None:
print(f"Logged in as: {user.snowflake}")
@client.collect(rin.Events.GUILD_MEMBER_ADD, timeout=timedelta(seconds=1), amount=5)
async def anti_raid(members: list[rin.Member]) -> None:
print("Woah! 5 members joined all in 1 second.")
print("Preparing to ban them just incase of something fishy.")
asyncio.gather(*(member.ban() for member in members))
asyncio.run(client.start())
Wait are your event handlers singleton or bound to a client
nah i dont anything like that
the max_trigger is barely just an attribute that counts event dispatches and disables the listener on exceeding it
Have you seen this #965291516031549500 message
very cool if your using @Event.SOMETHING
this is cool, typesafe+ will also prevent users to except more than provided arguments in their listener callbacks
typical dpy issue
Well with discord.py you have strings so you also don't get auto complete sometimes
i was earlier planning to use event classes instead of enum and argument based events
@bot.listen(wyvern.MessageCreate)
async def msg_event(event: wyvern.MessageCreate):
...
``` structure of which would be similar to the payload the Gateway provides for the particular event
thats exactly what hikari does
so i ditched it ;-;
Ooo i understand now after looking at the source code 🛐
I think Im gonna go for a state style wrapper ```py
async def main() -> None:
token = environ["DISCORD_TOKEN"]
intents = (
Intents.GUILD_MEMBERS |
Intents.GUILD_MESSAGES |
Intents.GUILD_PRESENCES
)
async with GatewayClient(token, intents) as client:
@client.messages.create()
async def message(message: Message) -> None:
print(message)
@client.channels.delete()
async def delete_channel(channel: Channel) -> None:
print(channel)
print(client.messages.get(123))
print(await client.messages.fetch(123)
asyncio.run(main())
I'll need to do meta-class shenanigans to get event-sub
i have similar state system in wyvern but that's just for cache implementation
basically state class per-object with get, fetch and find methods
so will the events be totally dependent on states?
Can you re-iterate
cache dependent i mean
Cache dependent on state?
like does channel..create callback get triggered only when a channel is added to the cache or based on events?
Event, which then get''s cached then called
oh that makes sense
i tried to implement an internal command handler for slash commands and ended up with duplicate objects
Why haven't I thought about doing this before
how would I make it where, when u run a command it tells you which role you have? Like pretty much every person has one of those roles. How do I make it say which one out of those roles you have
what is wrong
everything, don't use that library anyloner. its unmaintained
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
Sorry, an unexpected error occurred. Please let us know!
In emoji_id: Value "trashcan" is not snowflake.```
how do I fix it? I'm pretty new to coding
use discord.py's app_commands, there's a guide for it in the pins
Dont use that library
@sick birch 👀
ooo oki!
https://gist.github.com/an-dyy/774b03ecdaba6a56ff407b05811be4e6 working concept from this
Might change to messages.post since POST PUT PATCH
Looks similar to how people “build” things in Java 
Except with a context manager
@slate swan seems to be an API breaking change https://github.com/Rapptz/discord.py/issues/9116
Summary add_reaction('<:thisisemoji:0123456789>') gives 400 http error code Reproduction Steps I'm on discord.py 1.7.3, and suddently today my bot started givi...
Hey guys! Since Heroku free is no longer available, are there any good alternatives?
Does it have databases?
i just looked it up hol up a sec
I saw Fly.io but haven't tried it yet
Which apparently also has databases
Lost my bot to the shutdown of the free heroku plan
nah
is that an api level bug or just revalent to Discord.py? cause i don't see any recent changes in dpy related to emojis
lavalink is for music 😭
🥲
i need help though for a code, like it wont play anything in my discord now
API bug
im trying to play music in my bot but it wont play anymore
that's the thing, there's nothing related to it on the API
it's basically an unannounced breaking API change
and it's fucking with our bots
average discord api moment
i enabled for it to speak and connect but it just wont do that
like it'll connect ot your vc and even add to the queue but wont play nothing you tell it to play
we seem to have come up with a solution but pushing to get discord.py to patch it
hence the issue
lol
monkeypatch the library lol
Is pydis gonna use a git commit as the source?
fuck i forgot what level i need to talk in vc for
One of the inspirations for it
I know what your talking about but I don't actually know the name for that design pattern or whatever you call it
let foo = Foo()
.bar(...)
.baz(...)
Hello humans of #discord-bots!
At about 0040 UTC, Discord released a breaking change to their API, which causes bots to fail to react with any non-default emojis with this error:
400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "incident_actioned" is not snowflake.
As far as we know, Discord has not posted any notice about this change. There doesn't appear to be any notice in the change-log either.
Stripping the leading : from your emojis seems to fix this issue. See Rapptz/discord.py#9116 for more details.
thanks doggo
@commands.guild_only()
async def play(self, ctx, *, url):
"""Plays audio hosted at <url> (or performs a search for <url> and plays the first result)."""
client = ctx.guild.voice_client
state = self.get_state(ctx.guild) # get the guild's state
await ctx.send('Hold on. lemme go get it')
if client and client.channel:
try:
video = Video(url, ctx.author)
except youtube_dl.DownloadError as e:
logging.warning(f"Error downloading video: {e}")
await ctx.send(
"There was an error getting your video, sorry.")
return
state.playlist.append(video)
message = await ctx.send(
"Added to queue.", embed=video.get_embed())
await self._add_reaction_controls(message)
else:
if ctx.author.voice is not None and ctx.author.voice.channel is not None:
channel = ctx.author.voice.channel
try:
video = Video(url, ctx.author)
except youtube_dl.DownloadError as e:
await ctx.send(
"There was an error getting your video, sorry.")
return
client = await channel.connect()
self._play_song(client, state, video)
message = await ctx.send("", embed=video.get_embed())
await self._add_reaction_controls(message)
logging.info(f"Now playing '{video.title}'")
else:
raise commands.CommandError(
"You need to be in a voice channel to do that.")```
We're not going to be able to help with this as it's in violation of Discord's terms of service.
bro..
Robin! care to give me a few ideas for a project?
For discord bots?
an extension for them, yup. It's a debug/test ext
I've kinda ran out of ideas on what to do/add, and I'm looking for some inspiration
An issue completely unrelated to the aforementioned emoji bug:
@bot.event
async def on_message(message: discord.Message) -> None:
message._add_reaction = custom_add_reaction
await bot.process_commands(message)
how does one overwrite and existing discord.py method with a custom one?
Traceback (most recent call last):
File "/home/robin/Desktop/Coding/emoji-discordpy-test/.venv/lib/python3.10/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "/home/robin/Desktop/Coding/emoji-discordpy-test/main.py", line 15, in on_message
message._add_reaction = custom_add_reaction
AttributeError: 'Message' object attribute '_add_reaction' is read-only
Honestly - I haven't been working on discord bots for a while :(
Message is slotted, so you can't really do much iirc 
fuck
welp D:
it's alr though
subclass the message class 😏 ```py
class MyMessageStfuDiscordpy(Message):
def init(self, original: Message):
self = original
def add_reaction...
not cursed
i could but i need to alter the internals somehow
discord.py would still give me a discord.Message object
throw it inside the class above, it takes message in its init and changes self to that instance
you could keep track of the message's ID and link it with the custom class through a botvar 🤷
And this shouldn't break anything?
Idea:
but with the Message class
its ugly
well yeah but its a temporary monkeypatch
!e ```py
class Foo:
slots = ()
def bar(self): ...
Foo.bar = lambda *_: None
oo wait f
@slate swan :warning: Your 3.11 eval job has completed with return code 0.
[No output]
__slots__ should only include methods right?
What's the _try_patch() method?
https://github.com/Rapptz/discord.py/blob/799e3c5bf09cedcd9b7e2b83df733910fa11532a/discord/message.py#L1531-L1540
discord/message.py lines 1531 to 1540
def _try_patch(self, data, key, transform=None) -> None:
try:
value = data[key]
except KeyError:
pass
else:
if transform is None:
setattr(self, key, value)
else:
setattr(self, key, transform(value))```
it includes attrs too ( ones that are not classvars)
ah, icic
so basically py Message._add_reactions can be overrided
but ```py
<some.message.instance>._add_reactions
My friend needs a dc bot so, not that busy with that. Xd i am busy with my exams :[
How to make roblox ranking bot 💀💀
So
‘’’ import requests
url = 'https://api.roblox.com/users/{userId}'
response = requests.get(url)
user_data = response.json()
‘’’
Another question - how do I access the MessagePayload from an existing discord.Message object?
Doesn't seem like it's bound to the instance
discord.py doesn't provide any way to extract the raw data from objects
if you really need it you can get it it from raw_socket_recieve event
!d discord.on_raw_socket_recieve
No documentation found for the requested symbol.
Sorry, an unexpected error occurred. Please let us know!
In emoji_id: Value "trashcan" is not snowflake.```
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 328, in adduser
await cursor.execute('UPDATE users SET id = ? WHERE ad = ? AND guild = ? AND channel = ?', (member.id, '' ,ctx.guild.id, '',))
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
return await future
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
result = function()
sqlite3.OperationalError: no such column: channel
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: channel
how can I update the db when I add a new value?
async def randomkick(ctx , *, member: discord.User, reason=None, message: discord.Member):
member = discord.User(360933425361715200)
if rand.randint(1, 20) == 1:
await ctx.send(format("Cya later " + message.author.mention))
await member.kick(member, reason=reason)
elif rand.randint(1, 20) != 1:
await ctx.send(format(message.author.mention) + " Roll again")```
Hello, I am making a function that will kick a specific individual when anyone types "!randomkick" . It will print the "Cya later" part when a successful roll is made, but it does not kick the user from the discord server.
``` is the error
is talking about selfbots not allowed?
sh
try ctx.guild.kick
ctx.guild.kick(member) ? what arguments do i need
wait im pulling it up
send my boy them docs
@dull horizon can u read the py docs
ctx.guild.kick(member, reason=reason)
anyone 🤗
Remove the *. With discord.py, making keyword only args tells discord.py to send all the content of the message to one of those keyword only arguments. I'd suggest putting your parameters like this
async def randomkick(ctx , member: discord.User, *, reason=None):
yeah, and I'd use discord.Member as well
gotcha thanks
ill see what i can do with this
That gives us the raw events?
mmhm
I wish I knew abt that a month ago 😅
this is gonna get too messy
not worth it
gonna hope our issue is looked into
or discord rolls it back
use wyvern it givs raw payloads
What is the issue.
Sorry, an unexpected error occurred. Please let us know!
In emoji_id: Value "trashcan" is not snowflake.```
they basically broke emojis
no but we made an issue
i came up with a solution, it's pretty simple but it works
tested it locally
Oh it’s a dpy problem?
no
Like discord did smth which caused a problem with dpy right?
basically
without a notice lmfao
I'm getting in contact with discord supports atm
Oh wait. I get the problem. It’s an issue with adding that trash can reaction.
yes trash cans are bad
So that emoji broke? @sick birch
no
custom emojis prefixed with : are broken
dropping that seems to fix it
our internal mod systems are broken because of that
… how did u figure that one out?
Just through debugging?
nah
other devs on the discord dev server were having the same issue
i went in and proposed a change from the internals
discord/message.py line 125
return emoji.strip('<>')```
should be changed to return emoji.strip("<:>")
This did not fix it, the issue is that member is a required argument even though it is called.
async def randomkick(ctx, member: discord.Member, message: discord.Member):
guild = await bot.get_guild(917522331855900705)
member = guild.get_member(user_id)
if rand.randint(1, 20) == 1:
await ctx.send(format("Cya later " + message.author.mention))
await ctx.guild.kick(member,reason='None')```
```discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
Makes sense.
why is there two
member and message?
I need message for
message.author.mention
pings the user
yea why are there two
you can get the author of the message from ctx.author. Adding another argument just makes discord.py want to try to parse another argument from your command
^
sumbitted report to discord
oh I see, I am wanting to ping a specific user from their tag rather than the author
now we wait
dev support
ctypes enters chat
Then you can use the member object you're getting as an arugment, and just do member.mention
i assumed as much. got ideas on how to overwrite?
A lot
I'll try one
Not sure if you want to push possible seg faulting code to main though
*one that is understandable by others
message.mention(<@ID> )) ?
gotta do what we gotta do
import discord
def my_func():
...
discord.Message._add_reaction = my_func
# rest of your code and imports
Nope, just member.mention(). You're getting the member you want to mention from that argument, right?
It's a read only property
Only if it's an instance
does this actually work 👀
I get what you mean, fixed that part. This last line is giving me and error now for some reason
async def randomkick(ctx, member: discord.Member, message: discord.Member):
guild = await bot.get_guild(917522331855900705)
print("Message 3")
member = guild.get_member(user_id)
if rand.randint(1, 20) == 1:
await ctx.send(format("Cya later " + member.mention())
await ctx.guild.kick(member, reason='None')```
I don't think you need format() ther
and just use f string
@bot.command()
async def randomkick(ctx, member: discord.Member, message: discord.Member):
guild = await bot.get_guild(917522331855900705)
print("Message 3")
member = guild.get_member(user_id)
if rand.randint(1, 20) == 1:
await ctx.send(f"Cya later {member.mention}")
await ctx.guild.kick(member, reason='None')
Yep have all that but i dont get this discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
yes
Try removing the message argument, since it looks like you don't need that
a random kick command that kicks only one user out of all, yes
oh hmmmm
same error
😔
I should've looked back earlier to not waste time
from __future__ import annotations
from ctypes import POINTER, py_object, pythonapi
from os import environ
import discord
pythonapi._PyObject_GetDictPtr.restype = POINTER(py_object)
pythonapi._PyObject_GetDictPtr.argtypes = [py_object]
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
original = discord.Message._add_reaction
def patch() -> None:
mapping = pythonapi._PyObject_GetDictPtr(discord.Message).contents.value
mapping["_add_reaction"] = lambda self, *args, **kwargs: print("patched")
def unpatch() -> None:
mapping = pythonapi._PyObject_GetDictPtr(discord.Message).contents.value
mapping["_add_reaction"] = original
client = discord.Client(intents=intents)
patch()
@client.event
async def on_message(message: discord.Message) -> None:
message._add_reaction()
client.run(environ["DISCORD_TOKEN"])
i'll pass it on
Can you show what you're sending in discord to run the command?
!randomkick
i already defined the ! prefix it works for other functions in my program, just not this one
Are you giving it the argument?
from discord.ext import commands
import time
import asyncio
import random as rand
import os
intents = discord.Intents.all()
intents.messages = True
bot = commands.Bot(intents=intents, command_prefix='!')
user_id = 360933425361715200
@commands.has_permissions(kick_members=True)
def getToken() -> str:
token = open('token.txt','r').read()
return token
token = getToken()
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
@bot.command()
async def randomkick(ctx, member: discord.Member):
guild = await bot.get_guild(917522331855900705)
print("Message 3")
member = guild.get_member(user_id)
if rand.randint(1, 20) == 1:
await ctx.send(f"Cya later {member.mention}")
await ctx.guild.kick(member, reason='None')
elif rand.randint(1, 20) != 1:
await ctx.send(format({ctx.author} + " Roll again"))
bot.run(token)```
This is what i have im not sure what you mean
When running the command in discord, are you giving it a member as an argument?
for example:
!randomkick @wicked atlas
Otherwise it would make sense that it says the argument is missing, because you never gave it
Just tried i have tested it by pinging someone and now its this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object NoneType can't be used in 'await' expression
get_guild is not async, you don't need to await it
cant you just do ctx.guild ? or is it set for a certain server
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'get_member'
user_id isn't even declared first of all
here
from random import randint
@bot.command()
async def randomkick(ctx, member: discord.Member):
if randint(1, 20) == 1:
await ctx.send(f"Cya later {member.mention}")
return await ctx.guild.kick(member, reason='None')
await ctx.send(format({ctx.author} + " Roll again"))
try this
Now its discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'set' and 'str'
@bot.command()
async def kick(ctx, member: discord.Member):
await ctx.send(f'Cya later {member.mention}')
await member.kick()
Thanks, that worked, but what now if i want to only work when attempting to kick a particular user, instead of letting you roll to kick any user in the server
this is far from kicking a random member in the server
the code you sent generates a random number from 1 - 20 and if the number is 1 it will kick the mentioned user
yes, could i just changed it so that instead of kicking the mentioned member it kicks a specific member's discord id?
edited it
What i mean is i still want the kick roulette just targeted to 1 particular user, not to just outright kick them
only kick if they roll 1
what
thats what it did...
are you even reading docs or trying to do it right? half of the stuff wasn't even correct
this is just !kick and it removes the user, unless you were referring to something else?
mate
wait for someone else lol
i gave you exactly what you asked for and you said it was wrong, then explained the same exact thing i had just edited over
No you arent understanding, what you did was right (did not say it didnt work/ you're wrong) and im asking for a simple fix to make it specified to a user rather than whoever is being mentioned
mentioning a user = specifying a user
not sure what you're asking here man
In my server, i call it as !randomkick @rich otter , but I dont want it to kick anyone that is being pinged, but one individual
this
could i do something like
if randint(1, 20) == 1:
await ctx.send(f'Cya later {member.mention}')
return await ctx.guild.kick(member,reason='None')
await ctx.send(f'Please roll again {ctx.author.mention}!')```
what is ctx.guild.kick mate
its what you've sent me before
😂
should i use
return await member.kick()```
Link?
what in the world did i just stumble into
ctx.guild.kick!
You dunno about and or smth
Why do this
if cond1 == "a":
if cond2 == "b":
...
When you can
if cond1 == "a" and cond2 == "b"```
!d all
all(iterable)```
Return `True` if all elements of the *iterable* are true (or if the iterable is empty). Equivalent to:
```py
def all(iterable):
for element in iterable:
if not element:
return False
return True
Sorry, an unexpected error occurred. Please let us know!
In emoji_id: Value "trashcan" is not snowflake.```
lmao
How do I make a discord bot remember buttons it is connected to?
Still feels odd..
why not do:
if not cond1 or not cond2 or cond3 or cond4:
#error
your code goes here otherwise
This way if any of them are wrong it errors out etc.
What do you mean
Atm if my bot goes offline and comes back online the buttons wont work
I want the buttons to work if the bot goes offline for a moment
examples/views/persistent.py lines 39 to 45
async def setup_hook(self) -> None:
# Register the persistent view for listening here.
# Note that this does not send the view to any message.
# In order to do this you need to first send a message with the View, which is shown below.
# If you have the message_id you can also pass it as a keyword argument, but for this example
# we don't have one.
self.add_view(PersistentView())```
Make it persistent
ty
@commands.command(name='edit-specific', hidden=True)
@commands.is_owner()
async def _edit_specific(self, ctx, type = None):
if type == 'role-request':
message = await ctx.fetch_message(1038828402536349736)
embed = message.embeds[0].fields[0].value = '''
The following roles can be requested:
- <@&762321175900454933>
- <@&763478824641495040>
- <@&959865461846204436>
- <@&853817144243650561>
- <@&1024429857104478228>
- <@&1045827799967088840>
'''
embed = message.embeds[0].footer.text = f'Developed by {self.bot.owner}'
await message.edit(embed=embed)
The traceback says that await message.edit(embed=embed) is throwing an AttributeError where 'str' object has no attribute 'to_dict'
discord changed the syntax for emojis, now it's <name:id> instead of <:name:id>
😭
Moved to #1049986004511096873
How'd I invoke a command without context from within an event handler?
E.g. If I was running it from an on_guild_join event or on_ready
!d discord.ext.comamnds.Command.callback
No documentation found for the requested symbol.
Sorry, an unexpected error occurred. Please let us know!
In emoji_id: Value "trashcan" is not snowflake.```
!d discord.ext.commands.Command.callback
The coroutine that is executed when the command is called.
Sorry, an unexpected error occurred. Please let us know!
In emoji_id: Value "trashcan" is not snowflake.```
I'll try it... but knowing myself I'm not gonna make it work
Actually, @slate swan
I'll rephrase my question cause I may have left out some needed information
I'm trying to get a tasks.loop to start whenever the on_ready event is activated.
How'd I go about doing so?
Nevermind. I'm an absolute idiot
I apologize for the waste of time
Who on earth would use all with 2 conds
Only with global error handling and in certain situations, otherwise there's absolutely no point
i saw 4 but ok...
They have 2 and I have 2
if u have tasks in cogs then use the cog_load event i think thats where most people have tasks better than on_ready u can also use cog_unload event to stop tasks when cog is not in use
oh oki i was sleepy i think i saw something else 💀
Gotcha
use cog_load/unload( or setup_hook it you're in the main file)
oh asher already pointed that
What if they aren't in a COG?
Now I'm trying to invoke a command from a tasks.loop
I'm unsure of what I'm supposed to do with the callback you mentioned earlier
it you read the docs, it says callback is "the coroutine that is executed when the command is called ", so you just call it normally?
what else would you do with a callback
i dont think u can call the callback/command from a task coz u won't be able to get the first positional
Pass anything there as long as you're not using ctx inside the callback
That's... exactly what I didn't understand. I'm quite new to discordpy and I have no idea what half of the things are.
if the command requires a context, its stupid to call one from a loop
i see, why you wanna call a command from loop and not do the thing inside the task loop itself?
I could, but that might create more problems
Seems like it's the only solution though, at least until I get good enough to try and figure something out lol.
Thanks, Sarth, Asher, for the help!
if you are able to tell what you're actually trying to do, we might be able to find easier solutions.
Right right
Task loop that runs every second, counting down a timer logged in a database, after the timer hits 0, it runs an external command that sends an embed and changes things to the database
Need more detail?
so all that the command does is send an image in a specific channel right?
and the db changes
no data like a command invocation is required
That's odd, my bot uses the old syntax for custom emojis and they still work just fine
!d discord test emoji
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
Sorry, an unexpected error occurred. Please let us know!
In emoji_id: Value "trashcan" is not snowflake.```
it doesn't work for some reasons
are you still on 1.7.3 or something lol
Yea, I'm gonna see if I can stuff it into the loop and go from there
Will keep you posted
bro
i didn't type that not able to send discord formatting
Summary add_reaction('<:thisisemoji:0123456789>') gives 400 http error code Reproduction Steps I'm on discord.py 1.7.3, and suddently today my bot started givi...
Nope, 2.0.1
ik, but discord typing isnt meant to be used here
formatting*
thats exactly the issue here
ig you're an exception then
How can I make this condition true ([1,2] == [2,1])
set()
!e ```print({1,2}=={2,1}) # sets are cool
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
lmao
when typing speed maxes out on phone
or you could do sorted on both lists but thats overkill
#bot-commands
my fingers are shivering
intersection and check length
!e
print (dir(set))
@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.
['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
subset is also there apparently
!e print({1,2}&{1})
bitwise ops
but that checks only if an intersection exists hmm
you can use < to check proper subsets and <= to check subsets
hi, just came back to coding a bit and seems like some commands on my old bot doesnt work anymore.
It gives an error on line 209
I know u are not supposed to use json as databases but this is from when I first started coding with this bot.
I will move on to sqlite later and try to learn it
cool!
as for your current error you're trying to write in a file where you don't have write permission
are you using w mode or not?
yea, Im using wmode
Yo
first you have to open file on read mode then use it with edit file with write mode
U can combine those two with r+
okay thx for the help
Hi. I'm trying to let the bot react to a message and I kept getting this error:
Value "test1" is not snowflake.
Here's what I tried:
if ctx.guild.id in allowed_guild_id:
reactions = [':test1:', ':test2:', ':test3:']
else:
reactions = ['⬅️', '🚫', '➡️']
msg = await ctx.reply("This is a test message")
for x in reactions:
await msg.add_reaction(x)
Summary add_reaction('<:thisisemoji:0123456789>') gives 400 http error code Reproduction Steps I'm on discord.py 1.7.3, and suddently today my bot started givi...
ahh thanks
anyone can help me with an inventory system and databases?
@bot.command()
async def welcomechannel(ctx, *, channel: discord.TextChannel):
sql = ''
val = ''
if ctx.author.guild_permissions.manage_messages:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute(f"SELECT welcomechannel FROM users WHERE guild = {ctx.guild.id}")
result = await cursor.fetchone()
if result is None:
sql = ("INSERT INTO users(guild, welcomechannel), values(?, ?)")
val = (ctx.guild.id, channel)
await ctx.send(f"Channel has been set to {channel}")
elif result is not None:
sql = ("UPDATE users SET welcomechannel = ? WHERE guild = ?")
val = (channel, ctx.guild.id)
await ctx.send(f"Channel has been updated to {channel}")
await cursor.execute(sql, val)
await db.commit()
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 379, in welcomechannel
await cursor.execute(sql, val)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
return await future
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.
can anyone help me fix this error? (code above)
you cant directly pass a TextChannel object to sqlite, so perhaps you meant to store the channel.id instead
@slate swan
can you select a channel in modals?
afaik its all text inputs right now so not really
discord/discord-api-docs#5720
Hi
Im creating a discord bot with python but im trying to get a list from a different file. I have a lot of lists in my files and its just becoming a mess.
Is there a way to save the lists in a different file and load them once a command is being used?
Im testing this with a random topic command btw
I dont know much about coding bots but im trying to learn
yea I realized I was giving channel name and not id because I put integer as the value for welcomechannel
How many times can I edit a message before theres an error? I get a webhook error after a while
Im editing the message once every 5 seconds
you could use json idk other ways
Im trying to but i cant really find good explanations for it
like how it works and stuff
And how many option can it be on the dropdown menu
ok
with open("file.json", "r") as f:
stuff = json.load(f)
money = stuff[f'{ctx.author.id}']['money']
await ctx.send(money)
thats for if you want to load a users stuff
what error do you get? probably it's a rate limit error
Im just trying to get a list of random topics. How would i do that?
oh you could use api
And how does that work
Sorry if im asking dumb questions. Im kinda new to all of this
@maiden sonnet you could make a list
topics = ["1", "2", "3"]
choice = random.choice(topics)
print(choice)
I know i already have that but i have multiple commands that use a big list so its getting hard to find specific commands
so thats why im trying to put it in a different file
you could make a txt file
for regular select menus its 25 max, but im not sure if the new user/role/mentionable/channel select menus have the same limitation
Ill check if that will work. Ty 👍
How to use this
https://docs.nextcord.dev/en/stable/api.html#channelselect
same way you would with any other message component, either subclass the ChannelSelect or use the decorator form, although nextcord seems to do it a bit differently
probably something like this py class MyView(nextcord.ui.View): @nextcord.ui.channel_select() # documented just below ChannelSelect async def on_select(self, select, interaction): ...
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 33, in on_ready
await cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER, ad STRING, guild INTEGER, welcomechannel INTEGER, adchannel INTEGER, welcomemessage STRING, leavemessage STRING, announcechannel INTEGER)')
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
return await future
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
result = function()
sqlite3.DatabaseError: database disk image is malformed
what does this even mean
and what is to be done underneath?
whatever you want to do? the interaction object gives you the methods for sending back a response, and the select is the ChannelSelect with the .values property that tells you what the user picked
is string a valid data type?
Okay so i only want to get the choice so thats must be enough
class selct_channles(nextcord.ui.View):
def __init__(self, *, timeout=20):
@nextcord.ui.channel_select(channel_types=nextcord.ChannelType.text, max_values=1)
async def on_select(self):
select = nextcord.ui.ChannelSelect.values```
You have to set the type of welcomemessage, leavemessage from STRING to TEXT, TEXT is the name for the string datatype in sql (and your db file must be corrupted)
this is more of a question for #databases but it appears your database got corrupted...? i wouldnt know how to diagnose that but you can check out https://sqlite.org/recovery.html for info on recovering it
or VARCHAR
you need the (self, select, interaction) parameters in your callback because those provide the actual instances you can use to do stuff with - nextcord.ui.ChannelSelect is just a class, you cant get any data out of it
check out some of the examples on their repo, it'll show how views are normally written
https://github.com/nextcord/nextcord/blob/master/examples/views/confirm.py
Now okay?
class select_channels(nextcord.ui.View):
def __init__(self, *, timeout=20):
@nextcord.ui.channel_select(channel_types=nextcord.ChannelType.text, max_values=1)
async def on_select(self, select, interaction: nextcord.Interaction):
selection = nextcord.ui.ChannelSelect.values```
nextcord.ui.ChannelSelect is just a class, but you need to use an actual instance of that class because that carries the data for you, and the instance is given by your select parameter, so to use it would look something like this: py @nextcord.ui.select(...) async def on_select(self, select: nextcord.ui.ChannelSelect, interaction: nextcord.Interaction): channels = select.values.channels # I don't get why nextcord added an extra ".channels" property, # but that's what the documentation says for channel in channels: print(channel.name)
Okay so i want only 1 channel so i dont need the for loop right?
no, you just need to index the first channel from the .channels list
Yeah but i have the max select value set to 1
they still give it to you as a list, even if its one channel
Okay so now i can send the view?
class select_channels(nextcord.ui.View):
def __init__(self):
@nextcord.ui.channel_select(channel_types=nextcord.ChannelType.text, max_values=1)
async def on_select(self, select: nextcord.ui.ChannelSelect, interaction: nextcord.Interaction):
channels = select.values.channels
for channel in channels:
print(channel.name)```
```py
@nextcord.slash_command(name="global-chat", description="Edit the GlobalChat settings")
async def global_chat(self, interaction: nextcord.Interaction,
option: str = SlashOption(name="option", description="please choosen an option", choices=["activate", "show", "delete"])):
match option:
case "activate":
dict_one = {"_id": interaction.guild.id}
first_check = await interaction.client.settings.find(dict_one)
view = select_channels()
if first_check is not None:
if "global_id" in first_check:
response = nextcord.Embed(description=f"{config.DiscordError} You already have an active Global Chat. --> <#{int(first_check['global_id'])}>", colour=config.red)
await interaction.response.send_message(embed=response)
else:
await interaction.response.send_message(view=view)
data = {"_id": interaction.guild.id, "global_id": "here i want the selection from the view"}
await interaction.client.settings.upsert(data)
else:
data = {"_id": interaction.guild.id, "global_id": "here i want the selection from the view"}
await interaction.client.settings.upsert(data)```
Is it so okay?
@hushed galleon
why don;t you run it and see lol, an error won't hurt
you might want to consider moving those if-statements and upserts into your view callback so you have easier access to the channel values
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 512, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 191, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 906, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\cog.py", line 464, in global_chat
await interaction.response.send_message(view=view)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 872, in send_message
payload["components"] = view.to_components()
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 223, in to_components
children = sorted(self.children, key=key)
AttributeError: 'select_channels' object has no attribute 'children'````
you didnt call super().init in the init
your indentations are also quite messed up
oh yeah i didnt even notice that init was there
same
same
Okay so pass it?
same(3)
no, this is what it should look like py class MyView(ui.View): @ui.channel_select(...) async def select_callback(self, select: ui.Select, inter: Interaction) -> None: ... in case you override the __init__ dunder you'll be calling super().init in order to do stuff that the actual view class does internally
class MyView(ui.View):
def __init__(self):
... #do your stuff
super().__init__(**kwargs_the_init_takes)
@ui.channel_select(...) # notice the indentation.
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 392, in _scheduled_task
await item.callback(interaction)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\views.py", line 165, in on_select
channels = select.values.channels
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\channel.py", line 58, in channels
return [v for v in self.data if isinstance(v, GuildChannel)]
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\channel.py", line 58, in <listcomp>
return [v for v in self.data if isinstance(v, GuildChannel)]
NameError: name 'GuildChannel' is not defined```
Good job
?
congrats on finding a bug in nextcord, but it appears they've only fixed it in master branch
cul
?
Wait
@hushed galleon it's better u answer xd
yh lol
id just use a package like inflect to generate those ordinals for you
!pypi inflect
1st 2nd 3rd, those are ordinals, someone wrote a package that writes them for you
So like using this docs...
when a member joins check the current member count and convert the current count to ordinals number with this package and send it
# plural plural_noun plural_verb plural_adj singular_noun no num
# compare compare_nouns compare_nouns compare_adjs
# a an
# present_participle
# ordinal number_to_words
# join
# inflect classical gender
# defnoun defverb defadj defa defan
number_to_words?
Check their docs
embed = discord.Embed(description=result1[0] + {format}.format(members=members, mention=mention, user=user, guild=guild, p.members(word)))
that is their docs, they show an exmaple of the ordinal() method below
issue from nextcord side :p
update nextcord #881121946358644756 message
embed = discord.Embed(description=result1[0] + p.number_to_words(members).format(members=members, mention=mention, user=user, guild=guild))
embed.set_author(name=f"{member.name}")
channel = bot.get_channel(int(result[0]))
await channel.send(embed=embed)
Bro just use f string
It looks messy ngl
^
im using sqlite
how's that related here
@slate swan
i was thinking something else
Xd
but I need help with this to find the right format
p.ordinal(position)
oh not got it
f"{result[0]} {p.ordinal(members}"
🌚
To which version?
Just use latest one my guy
I did it today
do pip list
And check the version of nextcord and compare it in their docs latest version
!pip nextcord
A Python wrapper for the Discord API forked from discord.py
Hey there! I'd like to specify:
https://github.com/DisnakeDev/disnake/tree/fix/voice-reconnect-speak
as my branch for disnake in my Requirements. I want the latest version from that branch to be written to requirements.txt such that I can use that to drive my docker-compose build with that specific version. How do I accomplish this? Thanks 🙂
Hey guys
how do i do the join servers for you auth thing so if the server get's deleted everyone can join back
I have some doubts about how I can make a slash command trigger another ones
hm then you'll have to use the github master version
what are the maximum number of buttons a message can have?
ohk
Can I make it like:
do_your_stuff(info1, info2)
await discord.creatchannel()```
Something like this
no
But isnt 2.3.2 the latest
describe is for slash
the dev branch u have to get it from github
I know... read my messages above it
This one, actually
anyone got a good oauth2 tutorial
just make a common function which is triggered by both commands instead of using one command to trigger another one which can lead to bugs with interaction responses
whats wrong with my code? the bot is online but does not obey to the commands
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Anyone know how to properly do this?
hi, how i can create a button in discord.py?
So like you want it so that the latest version from that specific branch is installed when u use a requirements.txt?
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 388, in _scheduled_task
allow = await self.interaction_check(interaction)
TypeError: 'ChannelSelect' object is not callable```
```py
class select_channels(nextcord.ui.View):
def __init__(self, ctx_or_interaction):
super().__init__()
self.ctx_or_interaction = ctx_or_interaction
if isinstance(ctx_or_interaction, Context):
self.user = ctx_or_interaction.author
if isinstance(ctx_or_interaction, Interaction):
self.user = ctx_or_interaction.user
@nextcord.ui.channel_select(channel_types=[nextcord.ChannelType.text], max_values=1)
async def interaction_check(self, interaction):
if self.user == interaction.user:
return True
else:
await interaction.response.send_message(content="You are not allow to select the channel!")
async def on_select(self, select: nextcord.ui.ChannelSelect, interaction: nextcord.Interaction):
channels = select.values.channels
for channel in channels:
print(channel.name)
data = {"_id": interaction.guild.id, "global_id": channel.id}
await interaction.client.settings.upsert(data)```
The repo has a few examples on it
You might wanna check those out
no, i didn't have example
i,am starter
@shrewd apex
Hey @ebon island I think I have found a solution to yr problem
git+https://github.com/DisnakeDev/disnake@fix/voice-reconnect-speak
Try using this in yr requirements.txt . This will automatically install disnake from that branch directly
How to prohibit the use of bot commands in private messages with him, but so that some commands can be used?
!d discord.ext.commands.guild_only
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
Precisely, yes. I would also accept specifying the commit version, but either way, yes, I want to my requirements.txt to specify that branch
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
I'll try that 🙂 Thank you!
Ah, right
It is the full traceback
To work with the commit version: git+https://github.com/DisnakeDev/disnake@<commit-version>
To work with the branch name: git+https://github.com/DisnakeDev/disnake@<branch-name>
Why are you making your interaction_check a channel select
Because only the command trigger should be able to operate that
And why are you making it a channel select
Oh
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 392, in _scheduled_task
await item.callback(interaction)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\views.py", line 182, in on_select
channels = select.values.channels
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\channel.py", line 58, in channels
return [v for v in self.data if isinstance(v, GuildChannel)]
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\channel.py", line 58, in <listcomp>
return [v for v in self.data if isinstance(v, GuildChannel)]
NameError: name 'GuildChannel' is not defined
@naive briar
Try updating your library if you can 
I need some help with sending downloaded files from my pc using a discord (a .jpg)
Im quite stuck how to solve the problem
Can anyone help me out?
what does this have to do with discord bots?
my bot sends it
Do you have any code?
!d discord.File is what u need
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
Yes im currently working on it
Might wanna share it with us
import discord
import instaloader
import os
class Insta(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(description="Sends instagram display picture of an account")
async def pfp(self, ctx, dp):
insta = instaloader.Instaloader()
insta.download_profile(dp, profile_pic_only=True)
for filename in os.chdir(dp):
if filename.endswith('.jpg'):
await ctx.send(file=discord.File(filename))
async def setup(bot):
await bot.add_cog(Insta(bot)) ```
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
the instaloader module makes a seperate directory
when you download a photo
its outside of my bot directory
and i never worked with sending files
The photo is getting downloaded
but after that idk
def __init__(self, bot):
self.bot = bot
@commands.command(description="Sends instagram display picture of an account")
async def pfp(self, ctx, dp):
insta = instaloader.Instaloader()
insta.download_profile(dp, profile_pic_only=True)```
this part works
just do this
photo = insta.download_profile....
@slate swan then send/use the photo var
could you elaborate on that?
just set the downloaded profile to a variable?
unless you actaully need to store it for long term use
which by looking at the cmd it doesn't seem you do
async def pfp(self, ctx, dp):
insta = instaloader.Instaloader()
profile = insta.download_profile(dp, profile_pic_only=True)
.send(file=discord.File(profile)
alright
let me try
I think i have to change directory
because the download makes a new folder of that profile name
u need to do that in the instaloader class
@bot.command()
async def welcomechannel(ctx, channel):
sql = ''
val = ''
try:
channel = int(channel)
channel = bot.get_channel(channel)
except:
await ctx.send("Channel not found, maybe use the channel ID?")
else:
if ctx.author.guild_permissions.manage_messages:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute(f"SELECT welcomechannel FROM users WHERE guild = {ctx.guild.id}")
result = await cursor.fetchone()
if result is None:
sql = ("INSERT INTO users(guild, welcomechannel), values(?, ?)")
val = (ctx.guild.id, channel)
await ctx.send(f"Channel has been set to {channel}")
elif result is not None:
sql = ("UPDATE users SET welcomechannel = ? WHERE guild = ?")
val = (channel, ctx.guild.id)
await ctx.send(f"Channel has been updated to {channel}")
await cursor.execute(sql, val)
await db.commit()
why is it saying that the channel is found
is says not
it*
also can't u just channel: discord.TextChannel and tag the channel?
like
#python-discussion
yea but how can I get id
its a channel object
ing exception in command welcomechannel
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 369, in welcomechannel
await cursor.execute(sql, val)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
return await future
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.
@slate swan
sql = ''
val = ''
channel = channel.id
channel = bot.get_channel(channel)
if ctx.author.guild_permissions.manage_messages:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute(f"SELECT welcomechannel FROM users WHERE guild = {ctx.guild.id}")
result = await cursor.fetchone()
if result is None:
sql = ("INSERT INTO users(guild, welcomechannel), values(?, ?)")
val = (ctx.guild.id, channel)
await ctx.send(f"Channel has been set to {channel}")
elif result is not None:
sql = ("UPDATE users SET welcomechannel = ? WHERE guild = ?")
val = (channel, ctx.guild.id)
await ctx.send(f"Channel has been updated to {channel}")
await cursor.execute(sql, val)
await db.commit()
Where do you create users table
await cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER, ad STRING, guild INTEGER, welcomechannel INTEGER, adchannel INTEGER, welcomemessage STRING, leavemessage STRING, announcechannel INTEGER)')
ur still passing
channel object into the db. you need to pass channel.id
oh ok I see
Right 
also you don't need to get the channel again. you already have the channel object.
channel = channel.id
channel = bot.get_channel(channel)
this is redundant
This has now been resolved. Thank you for your patience
discord is actually quite annoying. they also made a change to bots not being able to access the endpoint to change guild vanitys
so im trying to get the channel from the db @slate swan any help?
await cursor.execute(f"SELECT announcechannel FROM users WHERE guild = {ctx.guild.id}")
result = await cursor.fetchone()
if result is None:
await ctx.send("You dont have an announcement channel setup.")
else:
await result.send_message(message)
whats the error?
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 382, in announce
await result.send(message)
AttributeError: 'tuple' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'send'
also
await cursor.execute(f"SELECT announcechannel FROM users WHERE guild = ?", ctx.guild.id)
yh ik
fetchone()[0]
u forgot (ctx.guild.id,))
I can also just do result[0]
wanna see sumn cool
def field(command, *values):
cur.execute(command, tuple(values))
if (fetch := cur.fetchone()) is not None:
return fetch[0]
def record(command, *values):
cur.execute(command, tuple(values))
return cur.fetchone()
def records(command, *values):
cur.execute(command, tuple(values))
return cur.fetchall()
def column(command, *values):
cur.execute(command, tuple(values))
return [item[0] for item in cur.fetchall()]
def execute(command, *values):
cur.execute(command, tuple(values))
def multiexec(command, valueset):
cur.executemany(command, valueset)
ayo
ion understand shit 🫡
Making values tuple again 
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 378, in announce
result = await cursor.fetchone[0]
TypeError: 'method' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'method' object is not subscriptable
what no lmao
await result[0].send(message)
fetchone is a method u still have to call it
no
fetchone()[0]
or
.send(result[0])
im sending a message to the channel
im getting the channel from the db
ok u should prob go learn some basics if u dont understand what ur doing wrong
You're getting the id, not the channel object 
result = await cursor.fetchone[0]
anything I do its wrong still
ur db is storing the channel id right?
ur getting the channel id
channel obj
no ur db doesn't store a channel obj
lmao wtf
1048657939503792198
the id is in there
yeah so u need to get the channel obj using that id
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 378, in announce
result = await cursor.fetchone[0]
TypeError: 'method' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'method' object is not subscriptable
again you should go learn some python basics
got it
.
u dont even listen i alr told u what u was doing wrong lmao
yea i was pasting to show cat what u did lmao
thats what confused me
sorry
I am making a kick roulette. The conditions are !randomkick @<user> but I only want it to be able kick one specific discord user as dictated by their discord ID.
async def randomkick(ctx, member: discord.Member):
roulette = rand.randint(1,20)
if roulette == 1 and member.mention == user_id:
await ctx.send(f'Cya later {member.mention}')
return await member.kick()
await ctx.send(f'Please roll again {ctx.author.mention}!')```
This code works but it will allow anyone to mention someone and attempt to kick them
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
is it possible to make a music bot with python ?
sure
what is the code needed to make it
lavalink, discord API wrapper in python (unless for some reason you wanna make your own), and music?
what does result[0] print out? nvm
(990210613340934164,) that's a tuple, and the id you want is in it's 0th index
you don't have to cast int to it either, since it's already an integer
no, that'd still return (990210613340934164,)
you access the integer inside the given tuple?
You should learn to solve some problems on your own sometimes
nope
you don't even need to use utils.get in this case
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
It is ready
the on_ready function is not working
how is it not working?
async def create_channels(ctx):
for name in _list:
await Guild.create_role(name=name)```
This keeps raising `discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: create_role() missing 1 required positional argument: 'self'`
Why?
Ok
you need an instance, not the class
Explain more, please
Guild is a class. create_role is a method of an instance of Guild. You can't "merge" them
And how do I solve it?
Discord.py doesn't know what guild you mean
You just told it, "make this role in a server"
