get_channel(id, /)```
Returns a channel or thread with the given ID.
#discord-bots
1 messages · Page 582 of 1
I think get_channel should work fine? Will probably return a CategoryChannel
Hm
yes
thanks
Wait what , discord.Bot?
oops my bad
discord.Client is
wrong library
yeah that's for pycord iirc
i need a code on how my bot gives someone a role whenever someone joins my server
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
How would I get the message that was interacted from in the “on_button_click” event
Use the on_member_join event, then add the role using member.add_roles
whether the type of target in classification shouldn't have boolean?
!d discord roles
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.
??
grrrr
For self-serving commands in #bot-commands
!d discord.Role
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
tyy
Ok
i think he's in the wrong channel
Perhaps
U can use discord.utils.get too
Cringe
What
No
If you have the ID never ever even consider using utils.get
I think discord.utils.get() is only useful if your looking for a channel that has the same name
^
Well it works too , w/e
yes
utils.get basically iterates over whatever array you give it, and checks if the name is equal with the one you gave
It does but using the ID is a lot better
discord.utils.get() is just a fancy name for a for loop xD
Well good in times of multiple guilds
whenever i try to run my bot it alwasy appears with this error
Exception has occurred: ClientConnectorCertificateError
Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]
The above exception was the direct cause of the following exception:
File "/Users/sadancooler/Documents/Code/Python/discord-bots/beginner.py", line 14, in <module>
line 14 is client.run('token') btw
Assuming the channel that we're looking for is discord-bots and that the array we give, is ctx.guild.channels, the only thing utils.get does is this ```py
for channel in ctx.guild.channel:
if channel.name == 'discord-bots':
return channel
im new to making discord bots through python but this crap annoys me
Or you could just store the channel ids in a database and not rely on utils.get
did u get rate limited?
wdym
hm
i just run and debugged through visual studio code
i can assure its not a vsc display issue because the bot actually doesn't turn online
That's a problem on your end, not with python nor discord, most likely an internet/address issue
Easier than storing, depends on situation, was telling cause it can be an option
try that ^
got it from https://github.com/Rapptz/discord.py/issues/4159 <=
i use mac tho
well I think theres a lock icon too on mac
yes
yes
you mean the "connection is secure" one?
How would I get the embed title from a message in a different function
idk not sure
well for me it says certificate is valid lmfao
its named beginner.py because im a beginner at this lmfao
get the message object > send the message embed title
A list of embeds the message has.
Ok
The title of the embed. This can be set during initialisation.
So I’m using a library that adds components to messages and I’m trying to get the embed title of a message that is in a command function in an event
I have a button click event
And a command that sends buttons
I’m trying to get the embed title when the button is clicked
same thing as I said earlier
👌
this is my code btw:
import discord # discord lib colors module set
from discord.ext import commands # fuck you i dont need to explain this
client = commands.Bot(command_prefix='!')
@client.event
async def on_ready():
print("WTF BRO") # print when bot is online
@client.command()
async def ping(ctx):
await ctx.send('pong')
``` there is client.run i just hid it becuase of the token
it wont freaking run
hm
Any errors?
Don't name your bot variable client, that's the first thing you should change
^
well he posted it earlier and you said something about it being a pc/browser problem
And yeah, any errors?
thats literally the example in the github, error is a sslcertificate thig
this mess
Install the certificate
how
^
?
Getting [SSL: CERTIFICATE_VERIFY_FAILED] on Python 3 on OS X?
Navigate to your Applications/Python 3.X/ folder and double click the Install Certificates.command to fix this.
Happy coding!
All of them are working if used correctly
how does mongodb the easiest db literally not work
🤔
How does that change anything
using another OS doesnt change anything
it does actually
what does
theres limited crap in c language which is what python is made from
Does anyone know how to use discord-components?
i think that crap is outdated
What isn’t outdated
i forgor
He forgor 💀
Is rapptz/discord.py good?
Idc anyway
I’m using discord-components
Nvm
Buttons
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
How do I install that
python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py
(you need python 3.8 or later)
I have 3.9 😎
pip install -U git+https://github.com/Rapptz/discord.py (you need python 3.8 or later)
Anyway I ran it
could if reaction.emoji == ":one:" or ":two:" or ":three:": works or i need to do
if reaction.emoji == ":one:" or reaction.emoji == ":two:" or reaction.emoji == ":three:":
Does it have an on_button_click event
Ofc
ypu might wanna check some examples
It's easy to use dpy 2.0 for buttons and selects
moblist = {
'mainmob' : {
'pig' : False,
'cow' : False,
'sheep' : False,
'villager' : False,
'witherskeleton' : False,
'blaze' : False,
'enderman' : False
},
'notmainmob' : {
'angrypig' : False,
'zombie' : False,
'angrycow' : False,
'spider' : False,
'angrysheep' : False,
'skeleton' : False,
'nitwit' : False,
'pillager' : False,
'magmacube' : False,
'zombiepiglin' : False,
'silverfish' : False
}
}
###############################3
async def area(message):
if area == 1:
for item in moblist['mainmob'].values():
item = False
for item in moblist['notmainmob'].values():
item = False
will this change all of them to false if some of them is true
Here are some examples
or just moblist['mainmob'] : False
moblist['notmainmob'] : False
Try it and see
You already got told what this does
its just this
how do i fix it
iterate all? and put all to false
The latter one but still Won't work,
I'm not sure if it will work in this format, the emoji thingy
It will make
moblist = {
'mainmob': False,
'notmainmob': False
}
Yes, as I already told you yesterday....
Mine isn’t working
for mob in moblist['mainmob']:
mob = False
for mob in moblist['notmainmob']:
mob = False
Show code?
like this?
Just try it and see please...
and did you check the examples?
from discord.ext import commands
from discord import FFmpegPCMAudio
bot = commands.Bot(help_command=None, command_prefix="j!")
@bot.event
async def on_ready():
print('ready')
DiscordComponents(bot)
@bot.event
async def on_button_click(interaction):
if interaction.component.label.startswith("play"):
channel = interaction.channel
await channel.send(interaction.message.embeds[0].title + " " + interaction.author.mention)```
Check the examples please
You didn’t even try
this is wrong someone help
hes using a 3rd party lib
It’s very confusing
No, he just installed v2.0
he was using discord-components earlier
tbh, It's way more simple than the library you are using
How the hell do I add buttons 😢
2.0
Ik
help
print(moblist['notmainmob['pillager']'])
this is wrong
How do I add buttons
examples folder pls
how to solve?
button(label=“f”) doesn’t work anymore
Check
Read the error
line 18
if self.values[0] == ["Moderation"]:
now good?
Did you even read the error
moblist = {
'pig' : False,
'cow' : False,
'sheep' : False,
'villager' : False,
'witherskeleton' : False,
'blaze' : False,
'enderman' : False,
'angrypig' : False,
'zombie' : False,
'angrycow' : False,
'spider' : False,
'angrysheep' : False,
'skeleton' : False,
'nitwit' : False,
'pillager' : True,
'magmacube' : False,
'zombiepiglin' : False,
'silverfish' : False
}
for mob in moblist().values:
mob = False
print(moblist[notmainmob['pillager']])
#################################################
#Traceback (most recent call last):
# File "<string>", line 22, in <module>
#TypeError: 'dict' object is not callable
help
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: call() missing 1 required positional argument: 'context'
class Confirm(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('Confirming', ephemeral=True)
self.value = True
self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('Cancelling', ephemeral=True)
self.value = False
self.stop()
bot = Bot()
@bot.command()
async def ask(ctx: commands.Context):
"""Asks the user a question to confirm something."""
# We create the view and assign it to a variable so we can wait for it later.
view = Confirm()
await ctx.send('Do you want to continue?', view=view)
# Wait for the View to stop listening for input...
await view.wait()
if view.value is None:
print('Timed out...')
elif view.value:
print('Confirmed...')
else:
print('Cancelled...')
yes, i read, but i cant understand it
huh, im nub
Go to your line 18
And figure it out
Or show the code here
wdym 18
line 18
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
Send Full traceback

class Pages(discord.ui.View):
def __init__(self, author: int, embeds: list, embeds2: list):
self.author = author
super().__init__(timeout=15)
self.embeds = embeds
self.embeds2 = embeds2
self.author = author
self.embed_count = 0
self.embed_count2 = 0
self.response = None
self.add_item(Menu(embeds2=self.embeds2))
async def on_timeout(self):
for child in self.children:
child.disabled = True
child.style = discord.ButtonStyle.grey
self.children[0].emoji = ":dl_arrow:"
self.children[1].emoji = ":dr_arrow:"
await self.response.edit(view=self)
async def interaction_check(self, interaction: discord.Interaction):
if self.author == interaction.user.id:
return True
else:
await interaction.response.send_message(f"This menu is not for you", ephemeral=True)
@discord.ui.button(label=None,
custom_id='1',
style=discord.ButtonStyle.red, disabled=True, emoji=":l_arrow:", row=2)
async def back_page(self, button: discord.ui.Button, interaction: discord.Interaction):
if self.embed_count > 0:
self.embed_count -= 1
self.children[1].disabled = False
if self.embed_count == 0:
button.disabled = True
await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=self)
if self.embed_count2 > 0:
self.embed_count2 -= 1
self.children[1].disabled = False
if self.embed_count2 == 0:
button.disabled = True
await interaction.response.edit_message(embed=self.embeds2[self.embed_count2], view=self)
@discord.ui.button(label=None,
custom_id='2',
style=discord.ButtonStyle.red, disabled=False, emoji=":r_arrow:", row=2)
async def last_page(self, button: discord.ui.Button, interaction: discord.Interaction):
if self.embed_count < len(self.embeds) - 1:
self.embed_count += 1
self.children[0].disabled = False
if self.embed_count == len(self.embeds) - 1:
button.disabled = True
await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=self)
class Menu(discord.ui.Select):
def __init__(self, embeds2: list):
menus = [
discord.SelectOption(label="Currency", default=True),
discord.SelectOption(label="Moderation")
]
super().__init__(placeholder=None, custom_id='3', min_values=1, max_values=1, options=menus, row=1)
self.embeds2 = embeds2
self.embed_count = 0
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "Moderation":
await interaction.response.edit_message(embed=self.embeds2[self.embed_count], view=self)
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Harckepy\Desktop\Voice bot\voicebot.py", line 107, in djboard
view = djboard()
TypeError: __call__() missing 1 required positional argument: 'context'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __call__() missing 1 required positional argument: 'context'```
Hello, could someone help me get the id of a channel by a command and put it in a variable to use it, the bot is in python
here is my code
@client.command()
async def aandd(ctx):
channel = discord.utils.get(ctx.guild.channels)
channel_aandd_id = channel.id
await ctx.send(channel_aandd_id)
Hey there
What's djboard
command
can anyone tell me why
In embeds.0.fields.0.value: This field is required
this error occurs
and my class name
class djboard(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey)
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
channel = interaction.channel
await channel.send(interaction.message.embeds[0].title + " " + interaction.author.mention)
await interaction.response.send_message('Confirming', ephemeral=True)
self.value = True
self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('Cancelling', ephemeral=True)
self.value = False
self.stop()
@bot.command()
async def djboard(ctx):
view = djboard()
e = discord.Embed(title=f'{ctx.author.name}\'s djboard | {ctx.author.id}', description="Your dj board sir")
m = await ctx.send(embed=e, view = view)
buttons = True
await view.wait()
if view.value is None:
print('Timed out...')
elif view.value:
print('Confirmed...')
else:
print('Cancelled...')
why tf you call a command like that
please
this bot is in py-cord or discord.py?
discord.py 2.0
It's moblist.values(), not moblist().values
ahh I see
because its what im used too
view = Confirm()
anyone?
yus, I am giving it
tbh, this is a pypi package command
and this thing works with most of the packages
but, not with some, for ex. aiohttp
oo thanks
so, I don't think so, that I am mission some kind of field
Well what do you put in the value of the first field of the embed
Print it
And you'll see it's sometimes empty
ok, I'll just print it!
moblist = {
'pig' : False,
'cow' : False,
'sheep' : False,
'villager' : False,
'witherskeleton' : False,
'blaze' : False,
'enderman' : False,
'angrypig' : False,
'zombie' : False,
'angrycow' : False,
'spider' : False,
'angrysheep' : False,
'skeleton' : False,
'nitwit' : False,
'pillager' : True,
'magmacube' : False,
'zombiepiglin' : False,
'silverfish' : False
}
for mob in moblist.values():
mob = False
print(moblist['pillager'])
output is true lmao
And it would be
print(moblist["notmainmob"]["pillager"])
i removed the mainmob and notmainmob thing
why is the for loop not working
Because you can't do it like that
You need to do dict[key] = value
The key would be the mob name and the value False
didn't seem to work I suppose
try:
author = info['info']['author']
if author is None:
raise Exception
except Exception as e:
author = "NA"
print(author)
...
wtf is that indent
someone ?
Example
for key.value in my_dict.items():
my_dict[key] = 1337
!e
x = {"a":True, "b":False}
x_new = dict.fromkeys(x, False)
print(x_new)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
{'a': False, 'b': False}
alright
Just add an argument to your command and type hint it to a channel. Then you can use
!channel #welcome
@slate swan
btw, ur username is quite funny!
Print author before the is None check
it comes as None
Does your exception even get raised?
dunno, lmao
basically, here the thing is, the author thing comes as "", but I try to take it as None
not sure if it is right or wrong
@slate swan :white_check_mark: Your eval job has completed with return code 0.
False
yeah, fixed it, "" was the issue
An empty string is not None
crap.
anything empty is None
No....?
Just proved you're wrong
!e print("" is None)
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False
lmao
False ^^^
i mean false*
Ah okay
Ignoring exception in command djboard:
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Harckepy\Desktop\Voice bot\voicebot.py", line 105, in djboard
view = djboard()
TypeError: __call__() missing 1 required positional argument: 'context'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __call__() missing 1 required positional argument: 'context'
!e
print(len(''))
class Confirm(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('Confirming', ephemeral=True)
self.value = True
self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('Cancelling', ephemeral=True)
self.value = False
self.stop()
@bot.command()
async def ask(ctx: commands.Context):
"""Asks the user a question to confirm something."""
# We create the view and assign it to a variable so we can wait for it later.
view = Confirm()
await ctx.send('Do you want to continue?', view=view)
# Wait for the View to stop listening for input...
await view.wait()
if view.value is None:
print('Timed out...')
elif view.value:
print('Confirmed...')
else:
print('Cancelled...')
```why, this is the exact cde from the example wtf
@slate swan :white_check_mark: Your eval job has completed with return code 0.
0
@slate swan :white_check_mark: Your eval job has completed with return code 0.
True
an empty string is always False

It's length == 0 == False
does they want to check if the length is 0 and then do something ?
It doesn't even matter
def check(string):
if not string:
return 'string is empty'
return 'no no empty'
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
Result is the same
you didnt print it?
why would i need to print it ?
Never called the function
you returned it
or that
its just an example 
smh
Then why eval it
And edit it like 2-3 times
Hoping to get output
i edited it only once to remove the eval


weird
how to solve?
You can't use [0] on a Pages object
okie
u meant this if self.view == "Moderation": ?
no error, but nothing happens
No I didn't say that
I never used views or anything similar
Just saying that you can't use [0] on a Pages object
That's basically what the error tells
how do i make a discord.ui button do something everytime it is clicked instead of it doing it conce and not doing it again#
!d discord.ui.View.stop
stop()```
Stops listening to interaction events from this view.
This operation cannot be undone.
^ I think idk
no, I want that when we send for example! welcome channel in a channel, the arrival messages are sent here (it's not very understandable)
Thankyou
So like
!welcome <channel>
no just !welcome in a channel
you’d get the ctx channel id
Do you have the id of the welcome channel?
dude
he said in the channel
They want to send in the welcome channel jeez
@client.command()
async def aandd(ctx):
channel = discord.utils.get(ctx.guild.channels)
channel_aandd_id = channel.id
await ctx.send(channel_aandd_id)
it's my code
et i want to get the id for another command
channel_aandd_id
my command is okay, but idk how to get the var [channel_aandd_id] for another command
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
Maybe you can get a use of this
@client.event
async def on_member_join(member):
channel = client.get_channel(channel_aandd_id)
embed = discord.Embed(title="welcome", description=f"{member.mention}", color=embedcolor)
await channel.send(embed=embed)
print(f"\033[1;31;40m event : member_join \033[0m")
this command
class DurationConverter(commands.Converter):
async def convert(self, ctx, argument):
amount = argument[:-1]
unit = argument[-1]
if amount.isdigit() and unit in ['s', 'm', 'h', 'd']:
return (int(amount), unit)
raise commands.BadArgument(message='Not a valid duration')
@bot.command(name='mute')
@commands.has_any_role("𝙊𝙒𝙉𝙀𝙍 👑","🔧│Developer-dc","𝙈𝙊𝘿","𝘼𝙙𝙢𝙞𝙣")
async def tempmute(ctx, member: commands.MemberConverter, duration: DurationConverter, reason=None):
channel = bot.get_channel(901138355239157811)
multiplier = {'s': 1, 'm': 60, 'h': 3600}
amount, unit = duration
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)
await member.add_roles(mutedRole, reason=reason)
embed = discord.Embed(title=f'Wyciszony!', description=f"{member.mention} został wyciszony. ", colour=0xb133ff)
embed.add_field(name="Powód:", value=reason, inline=False)
embed.add_field(name="Wyciszenie zostanie usunięte za:", value=f"{amount}{unit}", inline=False)
channel = await member.create_dm()
ban = discord.Embed(title=f" Zostałeś/-aś wyciszony/-a na serwerze McForever.eu, {member.name}", description=f" Powód: {reason}\n Na: {amount}{unit}\nZmutował: {ctx.author.mention}\n\n **Jak otrzymać unmute?**\n Napisz do osoby powyżej, która cię wyciszyła aby się odwołać (albo osóby z wyższą rangą).", color=0xb133ff)
await channel.send(embed=ban)
await ctx.send(embed=embed)
await asyncio.sleep(amount)
await member.remove_roles(mutedRole)
``` why bot dont wait when time end and give automaticly unmute
Then you can save it and use everywhere you want
no that dont work
Want to make per-server welcome messages or just for your server?
I get what you want to do
Just answer that question
You want to do !welcome and it saves the id of the current channel so that the welcome messages are sent in that channel
joinchannel = channel_aandd_id
@client.event
async def on_member_join(member):
channel = client.get_channel(joinchannel)
embed = discord.Embed(title="welcome", description=f"{member.mention}", color=embedcolor)
await channel.send(embed=embed)
print(f"\033[1;31;40m event : member_join \033[0m")
@client.command()
async def aandd(ctx):
channel = discord.utils.get(ctx.guild.channels)
channel_aandd_id = channel.id
await ctx.send(channel_aandd_id)
but that dont work
isnt channel_aandd_id a local variable
and how to do a local variable ?
That's your issue, it's local
It should be local
Use a bot variable
Then you can use bot.welcome_channel_id everywhere
Look at this
how ?
^
yees i know this but i want to get an id channel to put in the local variable
You said you already have the command working and sending the channel id
yes but .. the variable doesn't accept my variable [channel_aandd_id]
Does the correct channel id get sent?
joinchannel = [HERE, it's doesn't work]
@client.event
async def on_member_join(member):
channel = client.get_channel(joinchannel)
embed = discord.Embed(title="welcome", description=f"{member.mention}", color=embedcolor)
await channel.send(embed=embed)
print(f"\033[1;31;40m event : member_join \033[0m")
@client.command()
async def aandd(ctx):
channel = discord.utils.get(ctx.guild.channels)
channel_aandd_id = channel.id
await ctx.send(channel_aandd_id)
As I said 3 times
Use. Bot. Variables.
bot = commands.Bot(...)
bot.channel_id = default welcome channel id i guess
# In your event you can use bot.channel_id to get the channel id and send to it
@bot.command()
async def welcome(ctx):
bot.channel_id = the channel new id
mmh okay sorry
For specific commands?
yes
@reef shell Mentioned something about a GIST
you cant assign a variable to a variable that cant be accessed
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 359, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Harckepy\Desktop\Voice bot\voicebot.py", line 96, in play
message = await interaction.channel.send("playing music! " + interaction.author.mention)
AttributeError: 'Interaction' object has no attribute 'author'``````py
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey)
async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
message = await interaction.channel.send("playing music! " + interaction.author.mention)``` why
it was working before
😢
.
no it's okay that work
👍
@vocal plover Small question, are these indents made on purpose for copy paste or not?
probably on purpose
I don't want a "probably" answer, thanks
Gist
Simple Error Handling for ext.commands - discord.py - error_handler.py
^
is that discord.py beta?
I am switching to use falixnodes to host my discord bot. I think that it is a linux server powered by AMD Ryzen. My server is, i think a docker image. I installed all of the requirements, but I get an error: py line 77: ansyc def on_ready() ^ Invalid syntax I am using 3.8.8
its discord.py 2.0
you must use .user
why isn't this working
try:
users = await get_bank_data()
user = ctx.author
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
await open_account(ctx.author)
earnings = random.randint(300, 550)
person = ["Steve", "Karen", "Micheal", "Daniel Craig", "Donald Trump", "Joe Biden", "Elon musk", "Jake", "Dank Memer"
"Rick Astley", "Drake", "Jerry", "Anonymous"]
choice = random.randint(1, 2)
if choice == 1:
earning_embed = discord.Embed(title="Success!", description=f"\"Oh, you poor little beggar, here's {earnings} dogecoin(s)!\" \n-{random.choice(person)}", color=discord.Color.green())
users[str(user.id)]["wallet"] += earnings
with open("mainbank.json", 'w') as f:
json.dump(users, f)
await ctx.send(embed=earning_embed)
else:
responses = ["Imagine begging", "BRO GET A JOB", "Sorry I don't have money", "Nahhhhhh", "Get good", "coin.exe has stopped functioning.Please try again later", "What", "Stop your gambling addiction"
"how about a **no**.", "I lost money from you earlier."]
no_embed = discord.Embed(title="Failure", description=f"{random.choice(responses)}. \n-{random.choice(person)}", color=discord.Color.red())
await ctx.send(embed=no_embed)
except discord.ext.commands.errors.CommandOnCooldown:
await ctx.send("You are on cooldown")
!d discord.Interaction.user
The user or member that sent the interaction.
You made a typo: shoud be async, not ansyc
sad nois
Ignoring exception in command beg:
Traceback (most recent call last):
File "C:\Users\\PycharmProjects\Doge\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\\PycharmProjects\Doge\venv\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\\PycharmProjects\Doge\venv\lib\site-packages\discord\ext\commands\core.py", line 788, in prepare
self._prepare_cooldowns(ctx)
File "C:\Users\\PycharmProjects\Doge\venv\lib\site-packages\discord\ext\commands\core.py", line 772, in _prepare_cooldowns
raise CommandOnCooldown(bucket, retry_after)
discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 24.72s
sad nois
aint it obvious?
yes
you're on a cooldown
that function does not get called if you're on a cooldown
oh
Hes a computer developer and can create nft generation code, python is too hard for his skills
Then how do I send "you are on cooldown"
use on_command_error if you want to send something like "you are on a cooldown"
Ok
I use python lol
its an event
And u cant do basic things
.
T_T
whats the error
I solved it
nice
The tutorial explicitly says not to copy paste, they're there for consistent indentation across code samples or my brain would be angry at me lol
Haha copy paste go brrr
I wonder how they do the py thing
But if someone creates a new language
How would they paste code
what py thing
Python in discord
spaghetti code
meaning?
Nvm
Yo thanks
Asnyc
asnyc
Yeah so, kind of made for copy paste.
Otherwise the indentation would not be already at one level, at least nobody really makes that in documentations or other type of code samples.
No, as said, not made for copy paste, made so that my ocd wouldnt scream at me
hmm okay
🥸
So basically indented with the code that comes before that part of code, which is not in that code block
tho this reminds me I need to cause myself pain and try to remove the copy button in the compose theme
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
how to edit embed in Select view ?
await interaction.message.edit() - i tried this, it changed page, but selection doesnt change
you cant edit a select menu
ik
Yeah that's true x)
Anyways, you have a great day 
what do with that?
but i send embed and when i want choose selection - it must change this embed, it change, but select option doesnt change
show us the error
why bot dont wait when time end and give automaticly unmute
@boreal ravine There is none, ^
Have you tired to print amount?
in terminal nothing, bot just remove muted role when time dont end

?
hm
can anyone help me
Since it doesn't wait, try to print the variable amount that you give when using asyncio.sleep.....
Traceback (most recent call last):
File "main.py", line 18, in <module>
client.run(os.getenv('TOKEN'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
No because you never gave code or errors
my error
Give the token
In the bot/client.run
print(amount)?
bot/client.run("token")
yes
Coding
And since os.getenv("TOKEN") is None, then to need to create an environment variable called TOKEN and give the bot token as value
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey)
async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
message = await interaction.channel.send("playing music! " + interaction.user.mention)
``` how can i delete the message that is sent (await messsage.delete doesnt work)
nvm
or just use the delete_after kwarg when sending the message
hm
Do this.
@bot.command()
async def hiThere(ctx):
pleaseDontTouchMe = await ctx.send("D")
pleaseDontTouchMe.delete()
So that doesn't work?
I'm about to tell you the unknown. You put it in... Your code!
it's a view???
camelCase in Python? 
he probably uses javascript
I need help using buttons with discord.py
Someone said it is still possible
to use discord.py
who said it isnt??
!pypi dislash.py is a good 3rd party library for that.
@slate swan so what do
Finally! I achieved my goal. I can use buttons ^^
Thanks~
my bot creates a ticket on reaction, and sends a message in that ticket channel which has a reaction
how do i capture that reaction?
Is there a way to make the bot send unicode emojis?
Right now for eg it sends
🙄 even if I want it to send \🙄
Hi evreone
\:emoji:
can you give ideas discord bot plz
make a bot where it connects with fornite!!
@boreal ravine what do?
idk
you forgot await
!d discord.ui.button
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
disabled kwarg interesting
use eyes
The button...
it says right here

so emoji=":emoji:"?
yes
k

Worked
are custom emojis allowed in buttons?
🤔 i doubt they are not
they are who says you cant
mhm it takes a PartialEmoji object as an argument
troll
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.emoji.name: Invalid emoji
In components.0.components.1.emoji.name: Invalid emoji
In components.0.components.2.emoji.name: Invalid emoji`````py
hi guys, need some help here: #help-grapes , can someone have a look?
seems you are not loading your emojis
invalid emoji read the error
i want to use ⏸️ ▶️ and ❌
emoji = get(bot.get_guild(guild_id).emojis, name="name_of_your_emoji")```
i have put the names of these emojis in but its bot working
unicode it maybe
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey, emoji="arrow_forward")
async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
message = await interaction.channel.send("playing music! " + interaction.user.mention)
time.sleep(5)
await message.delete()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Pause', style=discord.ButtonStyle.grey, emoji="pause_button")
async def pause(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
message = await interaction.channel.send("Paused music! " + interaction.user.mention)
time.sleep(5)
await message.delete()
@discord.ui.button(label='Quit', style=discord.ButtonStyle.grey, emoji="x")
async def quit(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
message = await interaction.channel.send("Quiting out of djboard! " + interaction.user.mention)
self.stop()
await interaction.message.delete()
time.sleep(5)
await message.delete()
k
isnt there a place in this server to get unicode for emojis?
ip grabber no clicking that
can someone have a look here: #help-grapes ?
!charinfo ⏸️
Character Info
\u23f8 : DOUBLE VERTICAL BAR - ⏸
\ufe0f : VARIATION SELECTOR-16 - ️
Full Raw Text
\u23f8\ufe0f
Character Info
\u274c : CROSS MARK - ❌

https://cdn.discordapp.com/emojis/759569537908867072.png?size=96```
there is the code in the url
!charinfo ⏸️
Character Info
\u23f8 : DOUBLE VERTICAL BAR - ⏸
\ufe0f : VARIATION SELECTOR-16 - ️
Full Raw Text
\u23f8\ufe0f
!charinfo ▶️
Character Info
\u25b6 : BLACK RIGHT-POINTING TRIANGLE - ▶
\ufe0f : VARIATION SELECTOR-16 - ️
Full Raw Text
\u25b6\ufe0f
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
await interaction.response.defer()
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 423, in defer
await adapter.create_interaction_response(
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction``` i get this error but nothing wrong is happening, how do i stop thsi error because i want clean terminal
Code 🙏
What?
6
can someone help me to make to a fight command which makes people to fight each other by using moves such as kick,block,punch and each thing having its own value
i have made a json dic for that purpose so can anyone help me out?
any help pls?
you may be using <bot object>.wait_for('message') to check the kick block punch etc messages from the members in the game
with a check making sure its only from the author
deleted message
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
``` what can i do about this
wait
you have been ratelimited
and dont make so many api calls
how
stop api calling
by not calling the api
read what alec said
you can make only 50 api reqs in a second
wtfd r u even trying to do
yeah but i think i dont do so many in a second
How long does in usually take till new features, like the Discord events get implemented into the API?
well, you do
what r u doing with code
@bot.command(name="t")
async def tDef(ctx, *, userinput):
usersearch = "+".join(userinput.split())
baseurl = 'https://www.timeanddate.com'
url = baseurl + "/worldclock/?query=" + usersearch
request_page = urlopen(url)
page_html = request_page.read()
request_page.close()
html_soup = BeautifulSoup(page_html, 'html.parser')
searchtz = html_soup.find(id='p0')
if searchtz == None:
url2 = baseurl + '/worldclock/' + usersearch
request_page2 = urlopen(url2)
page_html2 = request_page2.read()
request_page2.close()
html_soup2 = BeautifulSoup(page_html2, 'html.parser')
searchtz2 = html_soup2.find(id='mp0')
await ctx.send(" ".join(searchtz2.string.split())[3:])
else:
await ctx.send(" ".join(searchtz.string.split())[3:])
import os
import discord
from discord.ext import commands
from urllib.request import urlopen
from bs4 import BeautifulSoup
any idea why i have so many api calls
?
guys how can I use item callbacks and interactions?
reafd examples 🆒
do you have one?
what r u using for interactions?
ok, I am just trying to create selectMenu
discord.ui.Select or discord.ui.SelectMenu
and if user selects role, do add him this role so he can see the channels he selected
do you change the bot's status at small time gap?
or , use replit?
yes
ah so , even if you dont get ratelimited , you do
replit uses shared ips
so basically even if someone else gets ratelimited 'due to you using the same ip you face it too
https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py to be more specific
ugh thats annoying
where can i host my bot
free mostly 24/7 and good
@client.event
async def on_ready(message):
print('We have logged in as {0.user}'.format(client))
await message.channel.send('Hello there')
can someone help me
?
i wanna do that
on ready does not take any argument
okay ill check it out
when the bot is ready it will send hello there
you would be using get_channel to get the channel you need
and send message
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
get the channel
and .send()
how do i get the id of the channel
The channel ID.
i need to define a new function for that?
you dont need to , just copy it from discord and paste it there
Ah, nevermind, I'm guessing you're asking how you find the id of a channel from discord
no
right click
oo
if you have the channel object then you can access the id attribute
developer mode right?
yessir
alright
which function do i write in
look it up, i left my bot dead in heroku
i thought the same ......@loud junco
i got that
now i need to write the get_channel thing
someone help
How long does in usually take till new features, like the Discord events get implemented into the API?
its discontinued
discord.py is discontinued
wdym?
they stopped working on it
*he
was it only one person?
yes , Danny aka Raptzz
so i'd have to create an own API call for that feature?
ig
or migrate to a maintained library
pycord seems to be the go-to
Ok, Thanks!
about the Server events , i didnt find any documentation at https://discord.dev too
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Seems like it will take some time till its implemented
please let me know if you find it eiscookie
channel = client.get_channel(channel_id)
await channel.send('Hello there')
yes
await channel.send('hello there')*
where do i add this thing
inside on_ready?
yes#
alright thanks
yes
guys, how can I install Rapptz discord.py in version 2.0? I did get some link from someone, but I would like to install it on another machine and I cannot find the link
to clone proper one
it has the latest version on master branch?
yes
pip install -U git+https://github.com/Rapptz/discord.py
make sure you have git installed
yeah it will update it ( -U will do that)
How can I remove “this interaction failed” message
no idea, but I saw there is is_finished() and on_timeout(), then you can disable those buttons and the message will not show up
when view times out you can make button disabled
but I did not find yet a way to remove this shit
I did not try it yet thou
can you confirm it works?
the command definetly works
no no
how can you work with buttons not to see this interaction failed message
yes, this shit
I proposed you disable buttons when on_timeout or is_finished()
or you coudl edit the message
i dont disable the buttons
ok, maybe edit the message
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey, emoji="\u25b6")
async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
message = await interaction.channel.send("playing music! " + interaction.user.mention)
time.sleep(5)
await message.delete()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Pause', style=discord.ButtonStyle.grey, emoji="\u23f8")
async def pause(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
message = await interaction.channel.send("Paused music! " + interaction.user.mention)
time.sleep(5)
await message.delete()
@discord.ui.button(label='Quit', style=discord.ButtonStyle.grey, emoji="\u274c")
async def quit(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
message = await interaction.channel.send("Quiting out of djboard! " + interaction.user.mention)
self.stop()
await interaction.message.delete()
time.sleep(5)
await message.delete()
then you refresh the timeout
thats my button code
in the docs
you have:
i have stop()
but when the message appears you still get what you want on callback?
yes
that is strange then, maybe try to make it persistent?
then timeout it None
so it should stay alive
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
await interaction.response.defer()
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 423, in defer
await adapter.create_interaction_response(
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction``` ```py@bot.command()
async def djboard(ctx: commands.Context):
view = Djboardcommand()
e = discord.Embed(title=f'{ctx.author.name}\'s djboard | {ctx.author.id}', description="Your dj board sir")
m = await ctx.send(embed=e, view = view)
@djboard.error
async def djboard_error(ctx, error):
if isinstance(error, discord.errors.NotFound):
return```
why am i still getting the error even though ium handeling it
o wait
i need to handle it on the buttons
seems that your interaction is not known, I guess you need some kind of ID for it or some ref
guys what are your thoughts on mongodb, is it safe or not
people tell me its easy to hack and it isnt safe
python recommends postgres
how do i make probability
but ask in #databases
wdym
like drop rate
random module
import random?
yes
pls do the module command
!d random
Source code: Lib/random.py
This module implements pseudo-random number generators for various distributions.
For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.
On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.
Similar names: django.random
thanks
this code snipped below helped to solve this issue?
idk what you mean by that answer
could you sample some code?
random module doesnt have probability ;-;
it does
@bot.command()
async def lock(self, ctx, member: discord.Member):
guild = ctx.guild
lockedrole = discord.utils.get(guild.roles, name="lockedrole")
if not lockedrole:
lockedrole = await guild.create_role(name="lockedrole")
await member.add_roles(lockedrole)
for channel in guild.channels:
await channel.set_permissions(lockedrole, speak=False, send_messages=False, read_message_history=True, read_messages=True, add_reactions=True)
await ctx.send("Locked")
?
it doesnt lock the channel
lemme read again
its a test lock i've never did it again
r u trying to do 30% chance it does this, %10 chance it does this
it doesnt lock the channel
its a test lock i've never did it again
import random
if random.random() < percentage_chance:
print('aaa')
random.random()?
!d random.choices for choices with probability
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.
alright thanks
import random
if random.random(0,100) < 34:
print('aaa')
if 67 > random.random(0,100) > 33 :
print('aaa')
if 101 > random.random(0,100) > 66:
print('aaa')
sure
thankss
hello
whats that
what?
psql
db i think
maybe random.randint
we are using it at work in our e-comm project, but I am not a big fun of it
oh
does Rapptz provide examples for discord 2.0?
yes
where?
actually i was making a code that each time my bot sees the string "I'm bored" it will ask to say a joke and each time you say no it gives the yes output
examples folder in master branch
im new to discord.py :/
make an event called on_message(message)
okay
if(message == "Im bored"):
channel.send("joke funny")
thats in the on_message(message)
event
yes
okay
channel = bot.get_channel(id)
to get the channel
or message.channel
okay thx
Hi Guys How To Write @buttons.click in cog
Pls Help Me
how do i check a reaction in a specific channel??
on_raw_reaction I think
then you need to filter it
1 sec
I do like this:
@bot.event
async def on_raw_reaction_add(payload):
if payload.channel_id not in omit_channels:
<some code>
if payload.channel_id == your_channel_id
oh so if i have a channel object name new_channel
if payload.channel_id == new_channel_id:
right?
wait
if isinstance(new_channel, discord.TextChannel):
if payload.channel_id == new_channel['id']
i got not defined error
https://cdn.discordapp.com/emojis/776192912899440690.png?size=48
can you show the error you are getting?
lemme try this
or you can you get()
new_channel.get('id')
or you can also ensure it has this attr
if isinstance(new_channel, discord.TextChannel) and hasattr(new_channel, 'id'):
no
if it is TextChannel it has id
so no sense to check it
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
await interaction.response.defer()
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 423, in defer
await adapter.create_interaction_response(
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction``````py
@bot.event
async def on_error(ctx, error):
if isinstance(error, discord.errors.NotFound):
m = await ctx.send("something has went wrong...")
time.sleep(5)
await m.delete()``` im handeling it and its still throwing the error 
Does this happen in a command?
on interaction with button
Then what event should you use?
I think it is independent form the code, the UI changes before on_error or something
No idea what this is.
idk thats why im asking
I don't think so.
No documentation found for the requested symbol.
!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 prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.9)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
@slate swan did you try to check view.is_finished() before handling interaction?
What
i'll try this now
Honestly I don’t know what your talking about
Me neither 
I have to test it 1st
@commands.Cog.listener()
async def on_guild_role_delete(self, role):
db = sqlite3.connect(f"{role.guild.id}.db")
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS suggestionschannel(guild_id INT, channel_id)")
cursor.execute(f"SELECT role_id FROM mutedrole WHERE guild_id = {role.guild.id}")
wynik = cursor.fetchone()
if wynik:
if role.id == wynik[0]:
cursor.execute(f"DELETE role_id FROM mutedrole WHERE role_id = ?", (role.id))
print("Dziala")
======================================================================
Traceback (most recent call last):
File "/home/kr3mu/.local/lib/python3.9/site-packages/nextcord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/kr3mu/Pulpit/AxisBOT/Eventy/roledelete.py", line 22, in on_guild_role_delete
cursor.execute(f"DELETE role_id FROM mutedrole WHERE role_id = ?", (role.id))
sqlite3.OperationalError: near "role_id": syntax error
on 2nd i got this
Role = ?”
yeah, there is no channel
Idk what you are doing but i recommend actually learning the syntax first. This is also the worst way to connect to a database let alone having a db per guild. Not to mention the fact that it is not async.
you need to define which one
new_channel = bot.get_channel(1024129854612421)
where the number is channel id
or you can just use the ID directly
how
then payload.channel_id == 0312953095732095792
but i cant know the id beforehand
to obtain ID
it makes it on the go
right click on the channel and "Copy ID" on the bottom
new_channel = client.get_channel(what to put there)
ID
no it makes it on the go
its like a temp channel
I recommend making your own function for this.
the bot makes it
no i dont have that channel now
you mean the channel?
its like a temp channel
ok
then you need to get it when you create_channel
Anyone know how to fix: KeyError: '331000144273342464' I have not found anything online (Python)
or whatever the method is named
yess exactly
it should return the channel
how do i do it?
I am not getting what you want
i want to check if a user reacted in a newly made temp channel
@bot.command()
@commands.has_any_role("moderator")
async def y(ctx):
dropdown_view = DropdownView()
dropdown_view.timeout = None
await ctx.message.delete()
await ctx.send("some msg", view=dropdown_view)
dropdown_view.timeout = None
you need to set timeout to None
then interaction will not die
how do i do that?
lets go pvt
def get_chan(self, chan_id: int, try_fetch=True) -> Union[discord.TextChannel, None]:
return self.bot.get_channel(chan_id) or (try_fetch and await self.bot.fetch_channel(chan_id))
It’s still raising th error
@slate swan this looks legit
still trying to understand
guys, can i make if self.values[0] == "Moderation":, which from Select class in Views class ??
You mean an enum?
union not defined?
from typing import Union
seems it is not happening after some time, but right away, is that correct?
right after you select a button?
thanks
Like a few seconds after
so this is occuring always?
I have no idea what these objects are.
how do i get a cha_id in first place?
Yes
each time you click?
Yes
hmmm
wait
I'm creating a giveaway command, only it doesn't work as expected
code:
async def giveaway (ctx, time = None, *, prize = None):
if time == None:
return await ctx.send ("Include a ** duration **!")
elif prize == None:
return await ctx.send ("Please enter a ** price **!")
embed = discord.Embed (title = 'Giveaway!', description = f '{ctx.author.mention} created a ** giveaway ** || Price: ** {prize} **')
time_convert = {"s": 1, "m": 60, "h": 3600, "g": 86400}
gawtime = int (time [0]) * time_convert [time [-1]]
embed.set_footer (text = f 'The giveaway ends in: {time}')
gaw_msg = await ctx.send (embed = embed)
await gaw_msg.add_reaction (": tada:")
await asyncio.sleep (gawtime)
new_gaw_msg = await ctx.channel.fetch_message (gaw_msg.id)
users = await new_gaw_msg.reactions [0] .users (). flatten ()
users.pop (users.index (client.user))
winner = random.choice (users)
await ctx.send (f "YAY! {winner.mention} won the ** giveaway ** || Price:` {prize} `")```
error:
from the console no one, only that when I enter the time and it expires, it does not send any notification, then it
does not add the reaction to participate in the giveaway
ok, so it is different issue
Ig
class Menu(discord.ui.Select):
def __init__(self, embeds: list, embeds2: list):
self.menus = [
discord.SelectOption(label="Currency", default=True),
discord.SelectOption(label="Moderation")
]
super().__init__(placeholder=None, custom_id='3', min_values=1, max_values=1, options=self.menus, row=1)
self.embeds = embeds
self.embeds2 = embeds2
self.embed_count = 0
async def callback(self, interaction: discord.Interaction):
assert self.view is not None
view: Menu = self.view
if self.values[0] == "Moderation":
self.menus[0].default = False
self.menus[1].default = True
await interaction.response.edit_message(embed=self.embeds2[self.embed_count], view=view)
elif self.values[0] == "Currency":
self.menus[0].default = True
self.menus[1].default = False
await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=view)
my Selct class
Well that is the channel id you are tyring to get the object from. This function returns that object if found.
need some help
what?
@discord.ui.button(label=None,
custom_id='2',
style=discord.ButtonStyle.red, disabled=False, emoji=":r_arrow:", row=2)
async def last_page(self, button: discord.ui.Button, interaction: discord.Interaction):
if self.embed_count < len(self.embeds) - 1:
self.embed_count += 1
self.children[0].disabled = False
if self.embed_count == len(self.embeds) - 1:
button.disabled = True
await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=self)
my button for pagination, i want if self.values[0] == "Moderation": this condition in this button
😔 i dont get it
can you share code again?
i just want chanel id of my newly created channel
or lets take some help channel @slate swan
when you create one it is not returned?
@slate swan let me know, this is interesting for me as I am doing something similar now
how do you make the channel
so new_channel should have id
curchannel is message.channel
Well new_channel already is the text channel object.
No need to get/fetch it really
yes how do i capture it
exactly!
just want to get its id
how do i get its id
new_channel.id
Can this event occur in a user DM?
Then payload.reaction.message.channel.id should suffice
thank you!
I really recommend using the docs since i did not knew this either i just searched it.
discord.py discontinued 😦
Wait change the variable to payload.channel_id
How are people finding this out now? It's so late lmao
okay?
That is the reason i recommend everyone to use disnake lol
And make everything slash commands. Since those will be mandatory later anyways.
oo
Looks good
i am inspecting my code
but ..how could it be
gotcha!!
Here's a better example than that
wait lemme fix it
!e ```py
a = 0
if a == 1:
b = 2
print(b)
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | NameError: name 'b' is not defined
!e ```py
x = 10
def foo():
print(x)
x += 1
foo()
@cloud dawn :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | File "<string>", line 3, in foo
004 | UnboundLocalError: local variable 'x' referenced before assignment
Ah i see, makes sense
Send the full code
Add print statements..
Debugging is your best friend
did , it doesn get prnted
i think i know a fix wait
Please use your own help channel, don't send your error in multiple places.
okay i am stuck
Me too
async def on_raw_reaction_add(payload):
if payload.member != client.user:
if payload.message_id in dict_of_colour_codes.values() :
await curchannel.send('hey hey it works')
new_channel = await curchannel.guild.create_text_channel(name=f'ticket - {payload.member}')
if payload.channel_id == new_channel.id:
await curchannel.send('well done')
print("part 2 was triggered")
if payload.message_id in dict_of_colour_codes.values() : how can this ever be true?
:) join my test server and see yourself
Now i also get your unboundlocal error
async def on_raw_reaction_add(payload):
if payload.member != client.user:
if payload.message_id in dict_of_colour_codes.values() :
await curchannel.send('hey hey it works')
new_channel = await curchannel.guild.create_text_channel(name=f'ticket - {payload.member}')
if payload.channel_id == new_channel.id:
await curchannel.send('well done')
print("part 2 was triggered")
``` this is how it should be indented.
This can also be shorter
i dont get it
whats different
async def on_raw_reaction_add(payload):
if payload.member != client.user and payload.message_id in dict_of_colour_codes.values():
await curchannel.send('hey hey it works')
new_channel = await curchannel.guild.create_text_channel(name=f'ticket - {payload.member}')
if payload.channel_id == new_channel.id:
await curchannel.send('well done')
print("part 2 was triggered")
Indention
ah



