#discord-bots
1 messages · Page 119 of 1
here let me show you what i did
my bot was working fine yesterday but i launch today and it doesnt print anything at all except for that?
Why are you doing try/except just to print out the error? Remove that
what's supposed to happen?
import discord
from discord import app_commands
from discord.ext import commands
#intents = discord.Intents.default()
#intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
try:
synced = await bot.tree.sync()
print (f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
@bot.tree.command(name='support')
@commands.has_role('verified')
async def support(interaction: discord.Interaction):
channel_name=(f"help--{interaction.author.name}")
guild = interaction.guild
existing_channel = discord.utils.get(guild.channels, name=channel_name)
if not existing_channel:
print(f'Creating a new channel: {channel_name}')
await interaction.guild.create_text_channel(channel_name)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.errors.CheckFailure):
await ctx.send('You do not have the correct role for this command.')
#bot.run('...')
What about it
File "/home/deusopus/make-a-channel.py", line 26, in support channel_name=(f"help--{interaction.author.name}") AttributeError: 'Interaction' object has no attribute 'author'
!d discord.Interaction.user
The user or member that sent the interaction.
ok
why does it keep saying appliction not responding. its working fine
it making the channel
I literally told you
Because you aren't responding
creating a channel isn't a response
jut had to restart it normally prints out so i know its on
interaction.response.XX is a response. Send a message, or defer
Why don't you have logging btw
Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using
Client/Bot.run. More about that in?tag defaultlogging.
It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging
but I can't use Client/Bot.run!
You can! You can load cogs and do other stuff in the newly added setup_hook method that is called once after the bot logs in, more about that and how to implement it in ?tag setuphook.
Hii!
So I have a friend that's trying to install discord.py on VS code, he got this error, anyone knows what's up?
U can use python 3.10
Instead of 3.11
Or follow the link in da error to get visual c++ 14 and then u can build the wheels
that's just vc code executing a command for you to run the file
I want to add a give command to my disocrd economy boy but I dont know how to type it in. Any ideas?
Im using SQL for my database
use a keyboard
Lol
have you done a class that let you do CRUD operations for your database?
"florida man makes programmer write his own ORM"
How to check if the bot is in the same channel as the user?
also ignore the bottom print(ctx.voice_state)
you don;t need to do that, but you can do that
nextcord is easier
for slash commands and for buttons
ctx.voice_client will give your bot;s client state, use it to get channel where the bot is in
oh thanks
!d discord.ext.commands.Context.voice_client
property voice_client```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
thats what i was looking for
yeah
i got it working now thanks so much
is my logic here broken? if i play a song when the bot is already in a channel then it says "Diffrent voice channel"
should be voice_client.channel
thanks
would you know how to check if ffmpeg is playing?
!d discord.VoiceClient.is_playing
is_playing()```
Indicates if we’re currently playing audio.
hello
i can't get this code to work
import discord, os
from datetime import datetime
from discord import app_commands, utils
from discord.ext import commands
class ticket_launcher(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
self.cooldown = commands.CooldownMapping.from_cooldown(1, 600, commands.BucketType.member)
@discord.ui.button(label="Create a ticket", style=discord.ButtonStyle.blurple, custom_id="ticket_button")
async def ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
ticket = utils.get(interaction.guild.text_channels, name = f"Support-Ticket-{interaction.user.name}-{interaction.user.discriminator}")
if ticket is not None: await interaction.response.send_message(f"You already have a ticket open at {ticket.mention}!", ephemeral=True)
else:
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction.user: discord.PermissionOverwrite(view_channel = True, read_message_history = True, send_messages = True, attach_files = True, embed_links = True),
interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True),
client.ticket_mod: discord.PermissionOverwrite(view_channel = True, read_message_history = True, send_messages = True, attach_files = True, embed_links = True),
}
try: channel = await interaction.guild.create_text_channel(name = f"Support-Ticket-{interaction.user.name}-{interaction.user.discriminator}", overwrites = overwrites, reason = f"Ticket for {interaction.user}")
except: return await interaction.response.send_message("Ticket creation failed! Make sure I have `manage_channels` permissions!", ephemeral = True)
await channel.send(f"{client.ticket_mod.mention}, {interaction.user.mention} created a ticket!", view = main())
await interaction.response.send_message(f"I've opened a ticket for you at {channel.mention}!", ephemeral = True)
class aclient(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
self.added = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id = '1037162557003276369'))
self.synced = True
if not self.added:
self.add_view(ticket_launcher())
self.added = True
print(f"We have logged in as {self.user}")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(name = "test", description = "testing", guild = discord.Object(id = '1037162557003276369'))
async def ticketing(interaction: discord.Interaction):
embed = discord.Embed(title = "If you need support, click the button below and create a ticket!", color = discord.Colour.blue())
await interaction.channel.send(embed = embed, view = ticket_launcher())
await interaction.response.send_message("Ticketing system launched!", ephemeral = True)
client.run('...')
i followed the instruction verbatim
its supposed to make a channel
but its giving me an error response
putting this in an if statement doesnt seem to work am i missing somthing?
if ctx.voice_client.is_playing: print("playing")
you mean like kick it?
is_playing()
its a method, not a property
oh my, thanks
any help?
what's the error
Application did not respond?
yeah something like that
you need to defer the response first because you're trying to do the ticket model before creating the interaction ( which takes more than 3 seconds (
its saying "This interaction failed"
ah
i need to launch it first
is what you mean right?
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
every time i append url to the queue it just rewrites over it
Your queue is a local variable
how can i fix it?
i want it to be able to be accessed in the play function, i haven't implemented it yet
I just realized something
Well uhh
I'm not allowed to help people about making music bots
Hello Guys how can i add Proxy for my discord bot ?
its okay i got it working
i had 2 funstions named play
lmao I found 2 bug with discord.py and disnake Voice implementation
probably nextcord and other fork are affected too
what is it?
@slate swan do you know the best way to tell when the voice client has finished playing the song?
https://github.com/DisnakeDev/disnake/issues/845
https://github.com/DisnakeDev/disnake/issues/846
the first issue was firstly found by a discord.py user
Summary A playing VoiceClient that gets moved in another VoiceChannel appear to stops reproducing the audio, though VoiceClient.is_playing() is True Reproduction Steps Join a VoiceChannel and repod...
Can someone help me with a mute command? Please, let it go well
anyone know what this means?
Traceback (most recent call last): File "/home/deusopus/random-button.py", line 15, in <module> class aclient(discord.Client): File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/button.py", line 281, in decorator raise TypeError('button function must be a coroutine function') TypeError: button function must be a coroutine function
here's the code...
import discord
from discord import app_commands
import random
yes_no = ["yes", "no"]
class random_bot(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
class aclient(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
self.added = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id = '1037162557003276369'))
self.synced = True
if not self.added:
self.add_view(random_bot())
self.added = True
print(f"We have logged in as {self.user}")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(name = "random", description = "answer yes or no", guild = discord.Object(id = '1037162557003276369'))
async def ticketing(interaction: discord.Interaction):
embed = discord.Embed(title = "Think of a 'yes' or 'no' question and click the button!", color = discord.Colour.blue())
await interaction.channel.send(embed = embed, view = random_bot())
await interaction.response.send_message(random.choice(yes_no), ephemeral = False)
@discord.ui.button(label="Yes/No", style=discord.ButtonStyle.blurple, custom_id="YN_button")
client.run("...")
its just a button when you press it it gives you a random yes or no
Is this for mute? It doesn't seem like much
are you working on a discord bot?
this is for people that are working on discord bots
How to show emotions for robots:
Custom emotes are represented internally in the following format:
<:name:id>
Where the name is the name of the custom emote, and the ID is the id of the custom emote.
For example,:python3:is the name:id for :python3:
When sending standard unicode/discord emojis, you just send the unicode character. This is handled differently from language to language, but in python, you can send \N{NAME}, the codepoint, \uFFFF, or just the unicode char itself: 🇦 You can get info on this by using the ?charinfo command
You can quickly obtain the <:name:id> format by putting a backslash in front of the custom emoji when you put it in your client.
Example: \:python3: would give you the <:name:id> format.
When adding reactions, you can either send the unicode for standard emojis, or send name:id, not <:name:id> for custom emojis.
New in 1.1.0 You can use <:name:id>
Animated emojis are the same as above but have an a before the name- ie: <a:name:id>
I already tried like this :IconSwitchIconOff:
did you even read what i sent
too long, didnt read
it still didn't work, it's in an embed that I want to put the emoji
show your code as a screenshot or pastebin
that should work as long as the emoji id and name are correct
*and its not an animated one, for animated you gotta add a before the first :
is the emoji animated?
no
How did you get the id
I sent it to chat and copied the id
😭 not another person who used message id instead of emoji id
how do i copy the emoji id?
thanks
ffs you could've just read it
yes
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')) ``` any fix please ?
How can i run a function when ffmpeg has finished playing a sound file?
Is this a recurring error?
dont use blocking libraries
you need a loop to check if VoiceClient.is_playing() is False
how do you make a discord.py button disappear after one use
btw currently there is a bug with VoiceClient.is_playing(), check Rapptz/discord.py#8483
you remove the button from the view and edit the message with the new view in the button callback
Is anyone here a gql wizard and can answer one (i think fairly simple) question to me by any chance?
don't ask to ask, just ask
!d discord.ui.View.remove_item
remove_item(item)```
Removes an item from the view.
This function returns the class instance to allow for fluent-style chaining.
Ok so when querying something i usually use
json_data = {
'operationName': 'ProfileByAddress',
'variables': {
'address': str(owner),
},
Returns a bunch of values, one of them is userID, is it possible to query for userID as well since thats all i have when using ctx.author.id
I´m not sure if in gql you can generally query for anything or if it needs to be setup with this query in mind, like an endpoint basically
i need the button to only work for the command creator
Or even: Can i just query without passing a variable and look through id´s on the return?
like this?
async def button_callback(button_inter: discord.MessageInteraction):
button1.disabled = True
no
this will disable the button, it will not remove it
are you using a view class?
cogs
so yes, you're using a View subclass
you're not subclassing right? you're usgin the default view classs
import random
import discord
from discord import app_commands
choices = ["yes", "no"]
class Buttons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Click me", style=discord.ButtonStyle.blurple, custom_id="button_yn")
async def click(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message(random.choice(choices))
class aclient(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
self.added = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id = '935395948727779328'))
self.synced = True
if not self.added:
self.add_view(Buttons())
self.added = True
print(f"We have logged in as {self.user}")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(name = "random", description = "random answer", guild = discord.Object(id = '935395948727779328'))
async def ticketing(interaction: discord.Interaction):
embed = discord.Embed(title = "Think of a yes or no question then click the button!", color = discord.Colour.blue())
await interaction.channel.send(embed = embed, view = Buttons())
await interaction.response.send_message("Random answer button launched!", ephemeral = True)
client.run("...")
where does it go in there?
discord.ui.View.remove_item(Buttons)
what library are you using
store the first message
msg = await interaction.channel.send(...)
then you should wait_for button_click (consider to use a custom_id so you can distinguish the button from the others buttons)
then you should edit msg removing the view, something similar, btw It would be easier changing other things in your code
there's no button_click event
so its not after the button sends a message
ah, I thought it also existed in Discord py
wouldn't it be right after the random.choice(choices)
anyway I think you can use on_interaction instead of on_button_click
await interaction.response.send_message(random.choice(choices))
no because you can't delete the first message that contain the view because it's not sent as an interaction response/followup, you're sending the message as TextChannel.send
hmmm
and you can't pass the message sent itself as View parameter
even in disnake it's just a wrap up of on_interaction with a check that interactiontype was button
ik but at least it exist
yeah, handy
so disnake
that's the way or respond to the slash command interaction with the view
what about if self.added = True then ....
something like this should work, although I'm not too sure now
class Buttons(discord.ui.View):
...
@discord.ui.button(...)
async def click(...):
...
await interaction.edit_original_message(...)
await interaction.response.send_message(...)
@tree.command(...)
async def ticketing(...):
...
await interaction.response.response.send_message(...)
...
oops that ticketing variable was left over from another project
or wait for interaction and check the components of the interaction, these are the ways
thanks though
is it possible to mention a user inside discord embed?
I just tested it can tag a user, but not showing yellow highlights
Correct, you cannot ping them in an embed only @ them
ohhh ok Thank you for the answer!
You could ghost ping them
Which sends message of ping and insanely deletes
I do it that way
i get this error in the log:
RuntimeWarning: coroutine 'playsong' was never awaited playsong(ctx)
but then when i put await playsong(ctx) i get:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object NoneType can't be used in 'await' expression
could you send your code?
Send full traceback of second exception please
how do you pick two items from a list?
and put them together in a print statement
nm
a_sample = random.sample(a_list, desired_number)
!d random.choices
random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
!e
import random
foo = ["bar", "egg", "bacon"]
print(*random.choices(foo, k=2))
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
egg bar
does this look right?
for i in range(1):
await interaction.response.send_message(random.choice(dice))
to throw two dice
oh nm,
That only fires one time, and why 2 messages?
hmmm?
sorry i didn't ralize you guys had answered
File "/home/deusopus/button1.py", line 18, in click
await interaction.response.send_message(random.choices(*dice, k=2))
TypeError: Random.choices() takes from 2 to 3 positional arguments but 7 positional arguments (and 1 keyword-only argument) were given
dont unpack dice
Do know the function returns a list so you can use str.join if you want to make it a string
okay so
dice = ["[ . ]", "[ : ]", "[ .: ]", "[ :: ]", "[ :.: ]", "[ ::: ]"]
these are the "dice"
Alright?
im trying to figure out how to just print two cleanly without being in a tuple
i was thinking of for i in range(1):
', '.join(tuple) maybe depends on how u want it formatted
bruh
sup
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
nothing hbu?
And I'm pretty sure it returns a list
mild fever and splitting head ache
``async def playsong(ctx):
url = queue_url[0]
print(f'url: {url}')
yt = pt.YouTube(url)
t = yt.streams.filter(only_audio=True)
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
path = Path(f"Downloads/{queue[0]}.mp4")
print(path)
print(queue)
if path.is_file():
print(queue)
print(f"Found Song {queue[0]}")
await ctx.send(f'**Now playing:** {queue[0]}')
voice.play(discord.FFmpegPCMAudio(path), after=lambda x=None: playsong(ctx))
queue.pop(0)
queue_url.pop(0)
else:
ctx.send(f"**Playing:** {queue[0]}.")
print(f"Downloading song {queue[0]}")
await ctx.send(f'**Now playing:** {queue[0]}')
voice.play(discord.FFmpegPCMAudio(t[0].download("Downloads")), after=lambda x=None: playsong(ctx))
queue.pop(0)
queue_url.pop(0) ``
and the calling is this
@client.command() async def skip(ctx): voice = discord.utils.get(client.voice_clients, guild=ctx.guild) print("stopped") voice.stop() await playsong(ctx)
and this error message "/env/lib/python3.9/site-packages/discord/player.py:711: RuntimeWarning: coroutine 'playsong' was never awaited
self.after(error)" but it still works
Does the weather have you like that?
yeah there has been few sharp changes recently
thx thx
I have a question
Yeah, ive got a cold because of the rain and weather where i live
how do I make a var for each guild
hope you get better!
so that each guild I cant run a command called $channel #channel and it will mark that channel
but it will work for all guilds
was that intentional or by mistake 👀
client.event
async def on_message(message):
q = await client.process_commands(message)
channel = message.channel
if message.author != client.user:
await channel.send(message.content)
await message.delete()
like this but instead of getting channel = message.channel it will do this for all set channels in all guilds
You can use a database or JSON depending on the size of the data but you should use an actual database over implementing a system with JSON
docs or something?
Mistake?
u replied to urself 
I was following up my statement lol
oh ic 
.
!d aiosqlite | you can use an SQL based db that stores data in a file, to learn SQL check out https://sqlbolt.com
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
No documentation found for the requested symbol.
!pypi aiosqlite
guess they dont have aiosqlite in the docs command
😦
You can't pass a coro to after kwarg of play
can you please elaborate
What kind of thing could I elaborate on
You just can't
Might want to use asyncio.run_coroutine_threadsafe()
why is utils in utils.get squiggly
import discord
from discord import app_commands
class Buttons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Click for support", style=discord.ButtonStyle.blurple, custom_id="001")
async def click(self, interaction: discord.Interaction, button: discord.ui.Button):
ticket = utils.get(interaction.guild.text_channels, name = f"Support-Ticket-{interaction.user.name}-{interaction.user.discriminator}")
utils.get is squiggly
thats not gonna work
what if two users have the same username
nvm
*two channels have same name
I didn't properly read ur code
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.
thats an easy fix
i'd just store channel id with respect to user id in sqlite3 table
https://paste.pythondiscord.com/sotuyehufe
error-
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\application_command.py", line 1542, in get_type
raise ValueError(
ValueError: SlashCommandOption ctx of command SlashApplicationCommand create-embed <function embed_create at 0x0000021F40537430> Type `<class 'nextcord.interactions.Interaction'>` isn't a supported typehint for Application Commands.
btw you can't have the same custom id for all of your views
apps command dont have context
tried removing and still
and you dont use self in a normal function
its for methods
ValueError: SlashCommandOption interaction of command SlashApplicationCommand create-embed <function embed_create at 0x0000021E04527430> Type <class 'nextcord.interactions.Interaction'> isn't a supported typehint for Application Commands.
oh
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.9: Required options must be placed before non-required options
ummmmm
all of them are false i didnt understand
nvm
forgot one it works
: Required options must be placed before non-required options
you probably have something like
def foo(option_one: str, option_two: str = None, option_three: str)
parameters having default values must be after required parameters
Does the discode bot also have traffic when hosting?
wdym ?
I wonder if there will be traffic if I buy hosting and run the bot in hosting.
When used by the user\
depends on your host
if colour:
embed.colour=int("0x" + colour, 16)
if colour is not int:
await interaction.response.send_message("Please provide a color with numbers! check out colorpicker.com")```
nextcord.errors.ApplicationInvokeError: Command raised an exception: ValueError: invalid literal for int() with base 16: '0xdsa'
How can I make a cog be the last to load?
load it at the last
how
depends on your code
🧠
why my terminal is not termination when i am using ctrl+c
it feels something is blocking the processes
for cog in target_dir.rglob("*.py"):
await self.load_extension(f"cogs.{cog.parent.name}.{cog.stem}")
I loead them like this
its frikkin saying utils not defined
File "/home/deusopus/ticketing_bot.py", line 11, in click ticket = utils.get(interaction.guild.text_channels, name = f"Support-Ticket-{interaction.user.name}-{interaction.user.discriminator}") NameError: name 'utils' is not defined
which library
well then you need to define utils. very helpful indeed
it's discord.utils btw or you from discord import utils
oh duh
the error pretty much tells everything, you can't compare an integer with a discord.Reaction object
depends on what starData is
you can typecast both of them to strings
and compare them that way
(utils:=getattr(__import__("discord"), "utils"))
```
🫦
just use filter() ;-;
!tag pos
Positional vs. Keyword arguments
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• !tags param-arg (Parameters vs. Arguments)
hello guys how do icreate an on_schedule_event_create() listener using the discord.Clients
the error is quiet self explanatory
i need the button to only work for the command creator
is it possible to make temporary buffs? For example + 15% to money from work for 2 hours?
yes
but as?
depends on you, you can do it with asyncio (the same thing is done with temp bans for example), create your own event system, or create a discord event, they're made through the dispatcher but it is not meant to be used so there aren't examples and there is no documentation about the dispatcher, yet you can look through the source code of d.py and look at how they're made
(await cursor.fetchall())[0]
what you're trying to achieve
why?
The logic doesnt make sense? How can a Reaction object be larger or equal than a number?
Yes? The attribute already returns a string?
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
Command raised an exception: TypeError: Type must meet VoiceProtocol abstract base class.
you can't interpret a Reaction as a number
I'm not sure what you want to achieve
@bot.command(aliases=["pl"])
async def play(ctx: commands.Context, *, search: wavelink.YouTubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
await vc.play(search)
embed = nextcord.Embed(title=f"**{search.title}**", description=f"> Now Playing: {search.title}\n> Duration: {search.duration}\n> Author: {search.author}", color=nextcord.Colour.random())
embed.set_footer(text="noice")
await ctx.reply(embed=embed)
elif not getattr(ctx.author.voice, "channel", None):
return await ctx.send("you have to be in voice channel!")
else:
vc: wavelink.Player = ctx.voice_client
if vc.queue.is_empty and not vc.is_playing():
await vc.play(search)
embe = nextcord.Embed(description=f"> Now Playing: {search.title}\n> duration: {search.duration}\n> author: {search.author}", color=nextcord.Colour.random())
embe.set_footer(text="noice")
await ctx.send(embed=embe)
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
ok sar
ytld😳
💀
hi noid
hi snipy✌️
opened 6 issues 
let me view them
most of them are the same issue
DisnakeDev/disnake#839
DisnakeDev/disnake#845
DisnakeDev/disnake#846
Rapptz/discord.py#9039
nextcord/nextcord#882
nextcord/nextcord#883
[discord.py] #9039 bug: await VoiceClient.disconnect() raise OSError: [WinError 10038] when passing a str that represent a non file-like object
[nextcord] #882 bug: VoiceClient.is_playing() returns True even when the bot doesn't reproduce audio (most likely there are some problems with packet loss?)
[nextcord] #883 bug: await VoiceClient.disconnect() raise an OSError: [WinError 10038] when passing a str that represent a non file-like object (e.g a url)
the voice implementation is really bugged
Yeah just saw them, i cant really comment about them as they're mostly about vc
There is a way to solve this but people don't bother debugging.
I think that if I try to test other classes I would probably find other bugs, it is something related to how the Threads that play the audio are handled
ok and
what should I do with that
when I have time I could try to do something, solving one of these problems will solve the others since the voice implementation has not changed
Most of the contributors dont make discord bots from what ive seen, only person ive seen carrying the library and testing and implementing new features has been arl, maybe we'll see a change in the future, maybe snipy will be the next big contributor
👀
have fun
yeah thanks for your concern
wait are you okimii??
I mean, okimii did that type of stuff nobody wanted, so....you changed your name?
no, okimii left his socials a while ago
I've been a contributor for just over 1 month and I already have 3 PR merged in disnake, who knows, maybe if I have enough time
btw I'm working on DisnakeDev/disnake#839 rn
👀
(and I have another PR waiting for rewiev (+400 lines diff))
DisnakeDev/disnake#837 if you want to take a look (mostly are changelog entry and docs but yeah)
How i can make a command show me in how many servers the bot and how many users and only owner the bot can use it
len(bot.guilds) for number of guilds
len(bot.users) for number of users
is_owner decorator for owner bot only
File "<string>", line 29
len(bot.guilds
^
SyntaxError: unexpected EOF while parsing
i oop
you're not oop
class MyView(discord.ui.View,discord.Interaction):
@discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary)
async def button_callback(self,button,interaction):
await interaction.response.send_message("You clicked the button!")
@discord.ui.button(label="Button 2", row=1, style=discord.ButtonStyle.primary)
async def second_button_callback(self,button,interaction):#
await interaction.response.send_message("You pressed me!")
@client.tree.command(name="msg_only", description="___")
async def _ping(interaction: discord.Interaction) -> None:
await interaction.response.send_message("pong",view=MyView())#,ephemeral=True
i'm getting this error:
AttributeError: 'Button' object has no attribute 'response'
how can i fix it ?
i'm still new with this API :/
You have your arguments in your buttons switched around
self, interaction, button ( order of args in a button callback )
thx
is there a way to say hello to members when they enter a certain channel?
yes i am
you're bad
get a room you two
your*
no

😳

*yro’ue
Hi, not sure if this is the right place to ask but, when I tried to install discord.py it told me that pip wasn't found. Someone sent me this link to download but I'm a bit confused of what to do https://bootstrap.pypa.io/get-pip.py
py -m pip install discord.py
download it and run it with python
And what command did you ran?
the one you sent me
py -m pip install discord.py
how am I meant to download it?
just click on the link, your browser should automatically start the download
or it will open the file in the browseer and you can use ctrl+s to save the file
uhh it didn't do any of that?
did it not start an automatic download?
no
what browser are you using?
well you'll have to open that directory in command prompt thats all
doesnt really matter yes
now open your command prompt and type cd "path where you placed the download" and then py get-pip.py thats all!
okay sucessfully downloaded discord.py
Or just double click on the file
yeah thats an option as well 
uh I didn't do that I just did
py -m pip install discord.py
that was for installing pip, for discord.py you gotta do what you did
But it worked without doing that
might have done this then
Sarth makes everything a tiny bit more complicated than needed.
It's a trait, honestly.
As long as it works at the end, it's fine
bro only windows has IDLE that runs on double click, and i havent touched that in months
for me it will just open the file in the default text editor
Sounds like an OS issue.
literally every non-windows os
I know
Hi again, I'm doing a command but I have a different layout which has multiple lines. What would I need to add to make it a separate line?
"""LINE1
LINE2
LINE3
"""
# or
"LINE1\nLINE2\nLINE3"
# or
"\n".join(["line1", "line2", "line3"])
yoo whats the equivalent of a server/guild in discord py? so i.e
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
server = str(message.guild.name) # this obviously isnt guild, so what is it?
print(f'{username}: {user_message} (#{channel} in {server} )')```
Okay I've done it all but now it just sends the same message 3 times
show code, and do you have a on_message listener with process_commands?
message.guild is the guild object
I've seppated lines with \
I think I know why
when I tested other commands, and now deleted them, they still work for some reason
you didnt restart your code
explain more please
also why doesnt this work? im trying to be able to send discord messages from the console
if message.channel.name == 'alabama' or message.channel.name == 'ai':
if message.content.lower() == 'Nerf Blaster 420!':
custom_message = input('Enter Your Text: ')
await message.channel.send(custom_message)
return```
but did you stop the old instance of the bot?
The message.guild attribute returns an object that represents a guild of discord by using OOP
uhh no
don't use blocking io in an async environment, input will freeze your bot completely
so how would i use it in this instance, like this?
you gotta do that first buddy
how?
blocking io ?
ctrl+c in terminal stops the process
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
What are you trying to do exactly?
add server to the console
hold on
⁉️
okay done all that, only one command is now working but it's still sending the message multiple times
so if someone sends a message it says pellko!: Raghh (posted in #ai)
i want it to say pellko!: Raghh (posted in {channel_name} in {server})
do you have an on_message listener/event
actually no i've not done it
so i.e pellko!: Raghh (posted in #ai in Python Discord)
ah
im doing ctrl c it's not working
.
nvm i did it
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
guild = str(message.guild.name)
print(f'{username}: {user_message} (posted in #{channel} in {guild})')
Quite unpythonic
f"> **Category:** {<#{s_channel.category_id}> if {s_channel_category_id} else 'No Category'}\n"```
Please help
I like your thinking ```py
print(f'{message.author.name}: {message.content} (posted in #{message.channel.name} in {message.guild.name})')
ok?
@slate swan can u help?
Too many str to str casts
just restart your device to reset the token and you're fine
For what
they have multiple bot processes running and are unable to stop them
owo
Bad token 🤗
I've been resetting the token and repasting it but it still gives me the error
Could you show your code
nope
Now could you show where you bring the token from on dev portal
do I have to do this every time I add a new code
Screenshot
I'd recommend using docker for better management
you'll have to restart the code everytime you make changes
or hot reload if you use cogs
ctrl + c works, thanks
anyone got a solution to my issue?
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
this error has also shown up
seems like im not authorised to use my own bot>
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.
if you get that while running the bot you just have the wrong token
i need help adding a point counter in my command where u can do !win @hollow gazelle and it adds 10 points to the file with the poiints they already have
show me how u have it being ran
e
its literally line after line aswell
so nothing is redefining it
I don't know how to tell you but it just simply can't be the right token
or he could just do py bot.run("token") insted of making it complicated or even just make a config
ill try that
Once you've reset it, could you show us the uncensored code with the previous token? Id like to see if it's in the right format
looks good to me
Seems alright, weird it's giving 401
same error
I don't think it's a rate limit
it might be
i dont think so
It would give you a 429
wait no rate limit is 428
im not getting rate limited on site either
429 mb
401 is unauthorised
no
im just trying to run it with python
its literally just a normal discord bot 😭
i just wanna test my code kekw
Has it ever ran?
Would you mind sharing the whole code?
why don't you just put the token within the bot.run function?
instead of making a variable?
import discord, traceback, random
from datetime import datetime
from discord.ext import commands
#bot configuration
prefix = "-"
bot = commands.Bot(command_prefix=prefix)
color = 0xc63939
bot.remove_command('help')
bot.donation_log_channel = 1037397123123126363 # enter the id of where you want donation logs to be sent to
bot.donationrole = 1037392038594891807
bot.suggestion_channel = 1037426350585282723
#enter the id of where you want suggestions to be sent to
@bot.event
async def on_ready():
print(f"{bot.user} is ready")
@bot.command()
async def help(ctx):
embed=discord.Embed(title="Commands",description="{prefix}embed [#channel] - Creates a custom embed\n{prefix}donate [@user] [donation] - Logs donations made",timestamp=datetime.utcnow(),color=color)
embed.set_footer(text="Developed by Fiery")
await ctx.send(embed=embed)
@bot.command()
@commands.has_role(bot.donationrole)
async def donate(ctx, member:discord.Member, *, donation):
channel = ctx.guild.get_channel(bot.donation_log_channel)
embed=discord.Embed(title="New Donation",description=f"Discord: {member}\nDonation: {donation}",color=color,timestamp=datetime.utcnow())
embed.set_footer(text="Developed by Fiery#6858")
await channel.send(embed=embed)
await ctx.send(f"{ctx.author.mention}, donation log successful!")
did that still didnt work
You don't have any intents.
ofc the bot run bit is under
i kept getting errors when defining intents
so i removed it
Did you use .all()
bot = commands.Bot(command_prefix=prefix,intents=discord.Intents.all())
that was how i defined intents
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
damn they changed it?
It has been like this for years, all is just defining that you want all intents but since a while you can't enable them all since some are privileged.
content isn't a valid intent
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
New in version 1.5.
eh so is it intents.message or
The blue title is an URL, there you can find all info about intents.
cant find anything about the message content intent
wait
im an idiot oh my goodness
it woould be like intents.message.administrator
no
What?
discord.Intents is a class with attributes and 3 methods. The attributes are by default False, if a attribute is set to True that intent is enabled.
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
New in version 1.5.
(click the title)
message_content
On the left there is a whole list of attributes.
thank you
So ```py
intents = Intents.default()
intents.members = True
intents.message_content = True
Yes
from discord import Intents
ik
Aka the embed told you.
You can use a variable from another module, e.g a config module and not on your main module to avoid leaking credentials of any kind, you can also use toml or json, really anything, do note some platforms like replit use envs for securing credentials
can someone help?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

Capital i
did that
no
i changed it cuz i thought it was lowercase
It's not
didnt work with capital too
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
New in version 1.5.
😂
Does someone know a guide in words (bcs I wanna learn something, not copy something) to make a discord bot?
If it didn't work with capital I it's a different error
And we'd like to see that different error
still shows same error
well that's not good
Could you show the code?

Just use discord.Intents instead of trying to import
It pollutes your namespace anyway
You don't have to import it
You'd just do something like discord.Intents.default() to get default intents
ah I see
Unfortunately there isn't one yet I'd recommend. Since Discord.py went downhill at the start of this year a lot of people gave up on it then moved to document Disnake, Discord.py got revived again and people stopped bothering.
mother fu
ohw okay tnx
Do you have any other files or folders named discord?
doubt it
@cloud dawn
on my entire pc?
It shouldn't be doing that unless you've got a broken install
No just in the project directory
my install is very old
definitely no
try pip show discord.py if the version is not 2.0.x
use pip install -U discord.py
x can be any number there
you either don't have discord.py installed at all, or have multiple versions of python
!minusmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
Using plain "pip" is not recommended
i uninstalled the lower version of python anyway
Specify which python version you're using with pip
can someone help me, it shows an error with intents
an error
Thanks for the help guys
Which could that be?
Prob the bare Client object that's crying.
Guessed right my friend
Is the error not clear enough?
how do i do that
!intents @keen vault
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Does \n go inside or outside speech marks
Inside
Alr
My new favorite way of calling strings.
it still has an error
Again.. what is an error?
How can i get all servers and invites to it from a bot in discord.py
so i wanna do that a member needs to setup a role
and he can choose any role how do i do that?
except socket.error, msg:
print("|[Connection Failed] |")```
why doesnt this work in 3.11?
bot.guilds
same error
For loop?
!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.
Did you save?
Did they remove !tb ..?
What's the new code look like now?
so i wanna do that a member needs to setup a role
and he can choose any role how do i do that?
And the invite for the server
!ytdl also
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
!d discord.Guild.create_invite
No documentation found for the requested symbol.
??
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") to do this.
There
!d discord.guild.channel.create_invite
No documentation found for the requested symbol.
Man this chat really turned into just !d
What have you got so far?
What exactly do you want? Buttons? Reactions?
Amazing how many problems can be solved by reading the documentation
i LOVE !D
I mean over the last hour it's juse been ToS violations and intents.
like when they do !helpmesetup <role.mention> and then it will do the role in the mention
Okay and what do you need help with?
how do i do the role mention and keep that thing
About average for #discord-bots then
Is it right?
embed = discord.Embed(description="Not important")
for server in bot.guilds:
inv = await server.create_invite(max_age=1, max_uses=1)
embed.add_field(name=server, value=inv)
await ctx.send(embed=embed)```
We'll not help with this for obvious reasons.
what is this even meant to do
Whats the reason?
Api abuse and privacy.
I must admit getting the invites for all of the servers your bot is in is.. strange
I want to inform the few servers that the bot will be deleted. It's a GlobalChatBot
class MyButton(nextcord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@nextcord.ui.button(label="Claim", style=nextcord.ButtonStyle.green, emoji=":NoaOkay:")
async def my_button(self, interaction: nextcord.Interaction, button: nextcord.ui.Button):
if interaction.permissions.manage_messages == False:
return await interaction.response.send_message(content="**You Cant Claim! Only Staff Can!**", ephemeral=True)
button.disabled = True
button.label = f"Claimed by - {interaction.user.name}#{interaction.user.discriminator}"
await interaction.response.edit_message(view=self)
@bot.command()
async def helpmesetup(ctx, member: nextcord.Member):
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = '**You have cooldown ! Please use this command again in __{:.2f}__s**'.format(error.retry_after)
await ctx.send(embed)
else:
raise error
@bot.command(aliases=["H"])
@commands.cooldown(1,30,commands.BucketType.user)
async def h(ctx, *,message='No Reason ! '):
check = ctx.author.voice
if check is None:
voice = f'The User Is Not Connected To A Voice ! '
else:
voice = ctx.author.voice.channel.mention
emeb12233 = nextcord.Embed(title='User:',description=f'{ctx.author.mention} Needs Help ',color=0x6c97c5)
emeb12233.add_field(name="Reason:", value=f'{message}', inline = False)
emeb12233.add_field(name="Voice:", value=voice, inline = False)
emeb12233.set_author(icon_url=ctx.author.avatar, name=ctx.author.name + "#" + ctx.author.discriminator,)
emeb12233.set_thumbnail(url=ctx.author.avatar)
await ctx.send(f"{staff_role}", embed=emeb12233, view=MyButton())
@bot.command()
async def gfcxfsedsa(ctx):
view = MyButton()
await ctx.send(view=view)```
@sick birch
How would you make embed welcome messages?
The Bot is only used by old friends @cloud dawn not Global
!d on_member_join
No documentation found for the requested symbol.
Add to every command that the bot is shutting down in x amount of days.
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
He only has commands
1 to activate the global chat
1 to deactivate the global chat
Then send a message from the bot to all general channels.
how can i make an embed out of modal ?
also how to make it send the response in a channel ??
Not a lot of experience with modals but you can use defer.
!d discord.ui.Modal.on_submit
await on_submit(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Called when the modal is submitted.
Seems like a viable method
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Your application was submitted successfully, {interaction.user.mention}!', ephemeral=True)
``` i have this on my `on_submit` rn
does anyone knows why it doesnt let my bot be public
like noit everyone can add it
Wdym?
That gets added manually.
@bot.command()
async def ping(ctx,self):
await ctx.send(f'Pong{round(self.bot.latency *1000)}) ms')
File "C:\Users\OneDrive\Desktop\AtomProjects\HyperionFund Discord Bot\main.py", line 136, in ping
await ctx.send(f'Pong{round(self.bot.latency *1000)}) ms')
AttributeError: 'str' object has no attribute 'bot'```
lil confused on what im doing wrong
show command
default auth link.
thanks!
command is here
bot is one file yeah
yea u don't need self
yup
f"Pong! {bot.latency * 1000:.2f}ms"
Faster way of rounding in a string format.
can you not ping in an embedded?
also the full text was run it back
Yep
@bot.command()
async def suggest(ctx, suggestion):
channel = ctx.guild.get_channel(bot.suggestion_channel)
embed=discord.Embed(title=f"Suggestion from {ctx.author.mention}", description=f"{suggestion}", color=color,timestamp=datetime.utcnow()
await channel.send(embed=embed)
await ctx.send(f"{ctx.author.mention}, suggestion successfully sent!")
how do I get suggestion to be the reminder of the text after -suggest
remainder
rather than just one word
also how would I use the authors username rather than their id
Can
I know you can no clue how though
Not in the title you can't
Like 5 mins I’ll show I
I didn’t see it’s in title
Generally don't mention in embed's since Discord mobile doesn't really format that really well.
how would I get it to say Fiery#8372
str(ctx.author)
str
also wouldnt it be ```
str{ctx.author}```
or do normal brackets work the same
someone help please again
Never seen this in any language ever lol
because ive currently got it in f" str{ctx.author}"
really thats how i was taught to do it in discord.py lol
its all over my code its kinda ugly ngl 
That's also fine, but then you don't need str
ight
also how do i get the variable suggestion to be equal to the remainder of the text after -suggest
currently its only taking the first word
I have no clue what you mean.
ok so the command is like -suggest run it back
seen that tut too
Ah ```py
@bot.command()
async def suggest(ctx, *, suggestion):
down there, member.mention*
send
wdym
like channel = bot.get_channel(id)
uh I didnt do that
does it matter where
its sending the welcome message]
profile_image = await load_image_async(str(member.display_avatar.url))
also do that
where exactly do I add ths
instead of channel = member.guild.system_channel
like its sending there the welcome msg w the original discord welcome msg
and if u want it to be dif then do that
what is the discord.py command to call a webhook
OH
like this?
- means that it imports all the stuff from easy pil
same errors
what imports do u have
.
and u did pip install easy_pil
yes
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.
like that
@bot.event
async def on_member_join(member):
channel = bot.get_channel(1035299325720408230)
background = Editor("pexels-quintin-gellar-313782.jpg")
profile_image = await load_image_async(str(member.display_avatar.url))
profile = Editor(profile_image).resize((150, 150)).circle_image()
poppins = Font.poppins(size=50, variant="bold")
poppins_small = Font.poppins(size=20, variant="light")
background.paste(profile, (325, 90))
background.ellipse((325, 90), 150, 150, outline="white",stroke_width=5)
background.text((400, 260), f"Dobrodošao/la na {member.guild.name}", color="white", font=poppins, align="center")
background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small, align="center")
file = File(fp=background.image_bytes, filename="pexels-quintin-gellar-313782.jpg")
await channel.send("Dobrodošao/la {member.mention}!")
await channel.send(file=file)
@bot.event
async def on_member_join(member):
channel = bot.get_channel(1035299325720408230)
background = Editor("pexels-quintin-gellar-313782.jpg")
profile_image = await load_image_async(str(member.display_avatar.url))
profile = Editor(profile_image).resize((200, 200)).circle_image()
poppins = Font.poppins(size=50, variant="bold")
poppins_small = Font.poppins(size=20, variant="light")
background.paste(profile, (320, 60))
background.ellipse((320, 60), 200, 200, outline="white",stroke_width=5)
background.text((414, 320), f"Dobrodošao/la na {member.guild.name}", color="white", font=poppins_small, align="center")
background.text((414, 260), f"{member.name}#{member.discriminator}", color="white", font=poppins, align="center")
file = File(fp=background.image_bytes, filename="pexels-quintin-gellar-313782.jpg")
await channel.send(f"Dobrodošao/la {member.mention}!", file=file)```
@keen vault try that
same errors
is that the only command u have?
i have 2
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.
Does anyone have a command for the avatar to go please?
Or server stats or user info?
Have you? I saw that you are good at it @slate swan
end = datetime.datetime.utcnow() + datetime.timedelta(seconds=time)
is this correct?
datetime.datetime is giving an error
but if i take away the first datetime then datetime is no longer red
Awww thank u, u can search in youtube it would be easier for you
U dont do datetime.datetime
Ok thx
Yes
im now getting an issue with timedelta
But imports
from datetime import datetime, timedelta
discord.utils.utcnow()+timedelta(seconds=time)
o
That should work^
so end = discord.utils.utcnow()+timedelta(seconds=time)
nice its working
I got confused on my giveaway bot code so i had to look up a working one and work from it
@slate swan will send u in a bit sorry
No worries!
Np
Oh okay gl!
thanks 😄
:)
new error 😦
users = await new_message.reactions[0].users().flatten()
im ngl i dont even know what flatten does
This was changed a new version
ah
It’s now users = [user async for user in users()]
Cause the users method now returns an async gen
Do u know list comprehension?
users = await new_message.reactions[0].user async for user in users()
Ah that makes more senswe
It would be [user async for user in new_message.reactions[0].users()]
Yes
alr
@bot.command()
@commands.has_any_role(964177601528725587)
async def win(ctx):
embed = discord.Embed(title="**5 PTS Added**", description="Your team has won `5 points`", color=0xfc0303)
await ctx.send(embed=embed)
ctx.send``` who can help me make it so when u @ the person jt adds points into a txt for them
@slate swan ive sent u a private message
@tree.command(name = "help", description = "Sends a list of Commands", guild = discord.Object(id = bot.guild_id))
async def self(ctx):
embed=discord.Embed(title="Commands",description="Staff Only Commands: \n **-embed [#channel]** - Creates a custom embed \n **-donate [@user] [donation]** - Logs donations made \n **-giveaway** - Starts a brand new giveaway (Needs Giveaway Host Role) \n **-reroll [channel] [giveawayID]** - rerolls the specified giveaway (Needs Giveaway Host Role) \n \n Fun Commands: \n **-8ball [Question]** - Ask the magic 8ball a Question! \n **-suggest [suggestion]** - Posts your suggestion in the suggestion channel \n **-ping** - shows the current ping of the bot",timestamp=datetime.utcnow(),color=color)
embed.set_footer(text="Developed by Fiery")
await ctx.send(embed=embed)
Im trying to convert all my commands to slash commands at the request of the admin
But im getting this error
nvm got it working
was botta
When using slash commands can I make it send a message in another channel
if so how would i go about doing that
who can dm me and help me with somthing if they have time
Hey, when I'm running this code, the bot only creates the slash-commands with the number 2 at the end and not the commands with the number 1, can someone help me?
Code: https://paste.pythondiscord.com/zegurohaca
yes you can but you can't use the Interaction object to do this
yeah i realised i can just do channel.send
just because its a slash command doesnt mean i cant use the normal command functions is what i realised
please could you tell the lines
where is the function, at what line
170 the bot creates the commands with nr.1 at the end
nvm found the problem
ah ok
you're creating two client object but running just one of them, basically you're overriding the old client object with a new one, fresh and empty (without app commands etc) so that's why all your nr1 functions aren't getting registered
btw I don't understand why you redefine the class and client
how do I get it to work?
what's the point of creating a new client object and redefine the client subclass?
try to delete the second subclass of discord.Client, and delete the Second client var too, initializes the client object only one time
@hollow agate are, you there?
Hi guys so im converting my commands to slash commands
@tree.command(name = "giveaway", description = "Create a giveaway", guild = discord.Object(id = bot.guild_id))
@commands.has_role("Giveaway Host")
async def giveaway(interaction: discord.Interaction, channel: discord.TextChannel, time: int, *, prize: str):
# Giveaway command requires the user to have a "Giveaway Host" role to function properly
try:
channel_id = int(channel)
except:
await interaction.response.send_message(f'You mentioned the channel wrong. This is how you do it: {interaction.channel.mention}')
return
channel = bot.get_channel(channel_id)
#Got a little confused to I may have borrowed some code from online lol
await interaction.response.send_message(f'The giveaway for {prize} will begin soon.\n Please go to {channel.mention}, the giveaway will end in {time} seconds.')
This is my code currently but when I put the channel in correctly I get the error that I mentioned it wrong
Can anyone help me with this logic error
Can you send the error?
Oh nvm there is no error because you have the except
Channel will give you the channel object. Are you just trying to make a post in it later in the code?
If all you're doing is throwing a post in it, I'd get rid of a few lines and just channel.send(message goes here)
dont i need the id
Not if they're giving you the channel in the slash command, you shouldn't
@mighty pilot can you help me?
The bot only creates the commands with nr.2 at the end because I have
class Aclient(discord.Client):
client = Aclient()
2 times
Can you help me to fix this? https://paste.pythondiscord.com/ipusivonul.py
so I can remove the except and just do channel.send
Give it a try, comment out the try and except stuff and send something with channel.send(). I'm not at my computer right now to look but I'm pretty sure I never had to grab a channel ID with my slash commands
k I got it working, but also how do I add a description to the individual parameters of the command
Are you using discord.py
Yes
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
so it would be @strange knoll_commands.describe(time="Entertime")
sorry for ping random dude
It looks like snipy already answered you
Up here
yeah, but I dont know how to fix it 💀
it goes here right?
No it goes under your other @commands lines
Just like the example in the embed up there
i guess
when I put the messageID im told its not a valid integer
What you mean
a user can open multiple tickets mb