#discord-bots
1 messages · Page 147 of 1
Bruh i just showed example
yes
Gimme ur code here
Let me edit
What command did you run
Just self
oh it didnt tag ok
!d discord.Client.get_channel
self.bot maybe
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
class ToS(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Agree", style=discord.ButtonStyle.green, custom_id="11")
async def new(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("Loading..")
You need to set label argument for every options
member=[]
class ToS(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Agree", style=discord.ButtonStyle.green, custom_id="11")
async def new(self, interaction: discord.Interaction, button: discord.ui.Button):
member.append(interaction.user.id)
await interaction.response.send_message("Loading..")
Check the error bruv
On line 210, shouldn't it be levelsys[0]?
Clearly saiid value and label is required
Because levelsys is an iterable
its there
thats right
After all, you checked whether its first item is not one
....
thanks, but how do i make it only respond to the users id.
i am still learning 😭
What do u mean?
Then they are None 🤷
my bot asks a question right, i want it only listen to what the user id /person says
now i got their id from the first button
Ohhh
if interaction.user.id in member:
msg = await bot.wait_for('message')
This should work
maybe its not showing the whole think or smt
Are u checking whether the role id exist or not
Or u checking the name
Idk db so imma not interfare
roleTF or leveleTF is truthy
You should print them
To see why
Wait, I just remove self?
What
Or what, cause self.user is my client
They're probably an iterable, too, because that's all what the call to fetchone returns
id
okay
U said “just self”, just self what
self is the client, self.user return ClientUser
OH
so zi need to do self.get_channel?
I*
Yes
It will be
if message.author.id in member
What the hell
Good
Print them before the last if in that command
okay
Omfg, ,send() got an unexpected keyword argument ‘embed’
if message.channel.id == 1011882292253294642 or message.channel.id == 1011881268285280316:
for emb in message.embeds:
chat = discord.utils.get(self.get_all_channels(), id=1047707576315420672)
embed = discord.Embed(title=f"[Ownerless Group]({emb.url})")
embed.add_field(name="id", value=emb.fields[0])
embed.add_field(name="name", value=emb.fields[1])
embed.add_field(name="Members", value=emb.fields[2])
print("1")
await chat.send(embed=embed)
print("4")```
(1036258095942340608,)
None
can you make it so my on_message command sends a embed if someone clicked a button
like it waits on someone to press the button
🤷
Check the documents
Didn't understand xd
Well then that role (@Helper) is registered in the database with some level, just not 3
where
yeah thats why i did another eol
search discord.py docs
@slate swan u got an idea about this? It be making 0 sense
What does it do
also try printing chat
It can be id tho no?
And what does this do
I saw in docs
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
It can be anything it can get from the objects
Cool
does the level twice but another role
Yeah I wrote this, but theres no module, so I tried installing the package, there is no Intents package, only intents
Send traceback
Maybe using diff library xd
How u get ur images to look like that, i love it
What are those two roles
can you make it wait until they click the ToS button, then send the rest of the code under the white line?
Check docs
No module named ‘Intents’
Bro
Add those line in ur f class
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
I mean ToS class
helper and special guest
loll shareX
Then of course it does not work
Traceback (most recent call last):
File "C:\Users\intel\Desktop\rijalbot\main.py", line 2, in <module>
import Intents
ModuleNotFoundError: No module named 'Intents'
Why are they there
Damn it dont work on ios right lmao
like under here right?
God
So mad pc way cooler
OMG
Import it from discord
bro he is genius kind of xd
FROM discord
It's not the command's fault it doesn't work. Something is adding these roles into the table with level 1 before you run the command.
The command fails because they're there.
tried even that and nothing
like this?
No, and u got many other errors
U gotta fix ur other error tho
?
U will see when u try it
Did u use the bottom and all?
Did u run it?
Button*
wait
U are breaking discord ToS
the id thing didnt work
how?
U are selling robux for USD
i just do this for fun
Yeah but its breaking discord tos☠️
im not selling it
Yes u are
Selling any item in discord = breaking TOS
He is selling and he is lying to me
its virtual + im not selling
His rate is 2.5k/1 dollar, so he isnt only selling but also scamming cause that rate is so false
Yes u are
no lol
yo anyone down to make an discord bot?
i do this for fun
☠️
🤷♂️
Why u lying?
so waht
okay
But u keep lying so ye rip u
ok
U banned me from ur scamming server lmaoo, finna get ur server term too
im scared
!d discord.ui.Button
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.
Try looking at the docs for once
Bro left the server, we had 3 mutual servers and he also left all of them💀
Aight guys, time to drop this, or take it to DMs, either way not here.
Do u even know what we are talking about?🤦♂️
whatever it is, its offtopic
I was legit telling him this was against tos and that he can’t get help here, so not off topic
just don't help them of they don't agree, stop wasting your time on the argument
Stop talking to me, u are saying off topic stuff
@slvl.command(aliases=['sr'])
@commands.has_permissions(administrator=True)
async def setrole(ctx, level:int, *, role: nextcord.Role):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild = ?", (ctx.guild.id,))
levelsys = await cursor.fetchone()
if levelsys:
if not levelsys[0] == 1:
return
await cursor.execute("SELECT role FROM levelSettings WHERE role = ? AND guild = ?", (role.id, ctx.guild.id,))
roleTF = await cursor.fetchone()
await cursor.execute("SELECT role FROM levelSettings WHERE levelsys = ? AND guild = ?", (levelsys[0], ctx.guild.id,))
leveleTF = await cursor.fetchone()
print(leveleTF)
print(roleTF)
if roleTF or leveleTF:
return await ctx.send("A role for that value is already exists! :x: ")
await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (True, role.id, level, ctx.guild.id,))
await bot.db.commit()
await ctx.send("Updated that level role!")```
and i set one role for level 1 and now tring to set a role for level 2 (which i only added one dif role for a dif level
Hello, I would like to make a bot which can translate different languages. is that possible?
yes
Can you please help me?
yes
!pypi deep-translator
all i have to do is install?
asher maybe u can help?
just use this lib and run it in a executor to prevent blocking
nope u are thinking too simple u need to code too
Yh I know
Like pip install deep-translator
whats leveltf and roletf
yes
await cursor.execute("SELECT role FROM levelSettings WHERE role = ? AND guild = ?", (role.id, ctx.guild.id,)) roletf
await cursor.execute("SELECT role FROM levelSettings WHERE levelsys = ? AND guild = ?", (levelsys[0], ctx.guild.id,)) leveltf
yeah i get that what do u get when u print those
(1036258095942340608,)
None
u know how operator or works? and what a if statement does?
then whats the problem the if statement evalutes as true hence u get the message
no cuz i dont have that role
like if i do the levelr command that show the rewards
( py @bot.command() async def levelr(ctx): async with bot.db.cursor() as cursor: await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild = ?", (ctx.guild.id,)) levelsys = await cursor.fetchone() if levelsys: if not levelsys[0] == 1: return await cursor.execute("SELECT * FROM levelSettings WHERE guild = ? ", (ctx.guild.id,)) roleLevels = await cursor.fetchall() if not roleLevels: return await ctx.send("No role levels has been setup!") em = nextcord.Embed(title="Role Levels", description="Role levels for the server", color=nextcord.Color.blue()) for role in roleLevels: em.add_field(name=f"Role Level", value=f"Level: {role[2]}\nRole: {ctx.guild.get_role(role[1]).mention}", inline=False) await ctx.send(embed=em))
it doesnt show it
look i got no idea about ur whole roles system backend and how u set up ur db and stuff that u gotta figure out on ur own the reason here is when u execute the sql query u are getting a role back which causes ur if statement to evaluate as true
if it were me i would just setup two lists of integers with level and role id in sql db with guild id as primary key
allrcs = [rc[1], rc2[1], rc3[1]]
how can I put these randomly in three button labels, like to choose one of these elements and put it randomly in a label and the rest of them randomly in the rest of labels
Which is the best library for a discord bot, now?
@bot.event
async def on_message(message):
msg = message.content.lower()
if msg == "gta":
await message.reply('Best Clan')
await bot.process_commands(message)
commands arent working
Unfortunately there are several libraries just for the purpose of developing a Discord bot. The "best" of them is one's own opinion, because they all let you develop a Discord bot.
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
use discord.py biggest community lots of support
I used discord.py before but i think it doesn't support slash commands
intents = discord.Intents.all()
already there
in dev portal?
It does since March or something
yeah
Yea I was inactive from march so didn't know
It was getting discontinued at that time
little help pls
It is no longer discontinued and it supports slash commands
They're called app commands in the library
Thanks mate
hey
i have a question..
so i have a discord bot and i want ppl to get role if they put smth in the status.. but i want to blacklist someone (they wont get the role)
You can read their activity but not their status.
You cannot get their status.
if value := self.children[0].value:
if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
await interaction.response.send_message(content="Url Invalid")
return
else:
embed.set_image(url=self.children[0].value)```How do I make a request to see if the URL points to an image with (aiohttp)?
Code?
Didn't I told you that already? :x
yes but i found out that you are not allowed to do this with requests it is best to avoid it with Discord bots
I would like to do it with aiohttp but I do not know how to do it exactly
What have you got so far?
What do you mean?
Make a head request then check the Content-Type from the headers
embed.set_author(icon_url=self.bot.user.avatar_url, name=f"{self.bot.user.name}")```
is this correct?
and how do I do that exactly?
There's no avatar_url property anymore in discord.py 2
!d aiohttp.ClientSession.head
coroutine async-with head(url, *, allow_redirects=False, **kwargs)```
Perform a `HEAD` request.
In order to modify inner [`request`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientSession.request "aiohttp.ClientSession.request") parameters, provide kwargs.
then?
Then what
2022-12-03 13:17:29 INFO discord.client logging in using static token
2022-12-03 13:17:31 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 53c0d18ca9c033e9c4056f6c208cb5b9).
RijalBot online
2022-12-03 13:17:41 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "rijalhelp" is not found
i mean replaced with?
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
#prefix for commands
rijalbot = commands.Bot(command_prefix='!',intents=intents)
@rijalbot.event
async def on_ready():
print("RijalBot online")
TOKEN = ''
rijalbot.run(TOKEN)
#commands
@rijalbot.command()
async def rijalhelp(message):
await message.send("test")```
!d discord.Member.display_avatar
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
Code never reached the command.
!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!
In this case .run() will never end.
So it waits till you shutdown the bot then it sees the command.
Ah so I should put the rijalbot.run after the commands?
Yep, basically unless you are doing some kind of async wrapper run is usually always at the bottom.
Thanks
how do you get discord version ?
why not just fetch it then check the headers
pip show discord.py
discord.__version__ ig not sure check ur autocomplete or maybe docs
import discord
from discord import app_commands
intents = discord.Intents.all()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
@tree.command(guild=discord.Object(id=556053478812942366))
async def test (interaction: discord.Interaction, name: str, age: int):
await interaction.response.send_message(f"{name}'s age is {age}")
@client.event
async def on_ready():
print(f"Bot is ready!")```
the command is not getting registered
Were did you sync?
these are some old commands
async with aiohttp.ClientSession() as session:
async with session.head(self.children[0].value) as resp:
img = await resp.read()
with io.BytesIO(img) as file:
embed.set_image(url=file)```like this?
sync what?
It's better to create a global session and use that rather than remaking and closing a new section everytime.
The commands, you need to sync them.
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
I recommend doing guild specific sync first.
where should i use this?
I put it in the setup_hook while in development.
should i put in on_ready?
It's the same as on_ready but with the name setup_hook
Not sure if it's an event tough.
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
and how ?
Either with a botvar or subclassing.
and how exactly should this go how should I include this in the code
bot.http_session: ClientSession = ClientSession()
async with bot.http_session.get(...) as resp:
...
oh so and how is that supposed to work now with Content-Type as Catgal explained?
how to include client.setup hook>
can you please show an example 😅
🐈
from discord import Client, Intents
class CustomBot(Client):
def __init__(self) -> None:
super().__init__(intents=Intents.default())
async def setup_hook(self) -> None:
...
...
thank youuuu
x = datetime.datetime.utcnow()
accountAge = (x - user.created_at).days```
accountAge isnt working
@uneven apex This URL also shows how to link a specific guild for development purposes.
👍
anyone
I don't know what you mean
I meant that I want to set the names in the labels randomly and the names not to be the same like this:
the rcs are the random choice for the names
!d random.sample if u want pick
random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).
Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
!d random.shuffle if u wanna shuffle
random.shuffle(x)```
Shuffle the sequence *x* in place.
To shuffle an immutable sequence and return a new shuffled list, use `sample(x, k=len(x))` instead.
Note that even for small `len(x)`, the total number of permutations of *x* can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.
Deprecated since version 3.9, removed in version 3.11: The optional parameter *random*.
hmm
He needs correct + 2 random from what I understood
Probably this is fine
choices = set(all_choices)
correct = ...
choices.remove(correct)
variants = [correct] + random.sample(list(choices), 2) # well involves sampling sorry
random.shuffle(variants)```
!e ```py
import random
from string import ascii_lowercase
all_choices = list(ascii_lowercase)
choices = set(all_choices)
correct = "e"
choices.remove(correct)
variants = [correct] + random.sample(list(choices), 4)
random.shuffle(variants)
print(", ".join(variants))```
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
w, y, o, e, z
how do you fetch members of a guild?
hello.
random.choices(imagesz, weights=(70,70,60,50,50,50,10), k=1)
i put this in my code
in the images there a links to photos
but when i run this
instead of showing picture it shows like this
['https://cdn.discordapp.com/attachments/1019185962196140042/1019186514971869215/IMG_6778.png']
can anyone help?
i dont wantr the [' '] in the output
i only want the link can anyone help me?
File "c:\Coding\CWL Bot\main.py", line 27, in <module>
client.run('token')
File "C:\Python 10\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Python 10\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Python 10\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Python 10\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Python 10\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Python 10\lib\site-packages\discord\client.py", line 589, in login
await self.setup_hook()
File "c:\Coding\CWL Bot\main.py", line 12, in setup_hook
await self.tree.sync(guild=my_guild)
File "C:\Python 10\lib\site-packages\discord\app_commands\tree.py", line 1059, in sync
commands = self._get_all_commands(guild=guild)
File "C:\Python 10\lib\site-packages\discord\app_commands\tree.py", line 740, in _get_all_commands
commands = self._guild_commands[guild.id]
AttributeError: 'int' object has no attribute 'id'
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001CD09F19EA0>
Traceback (most recent call last):
File "C:\Python 10\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Python 10\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Python 10\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Python 10\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
import discord
from discord import app_commands
my_guild = 556053478812942366
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=my_guild)
await self.tree.sync(guild=my_guild)
intents = discord.Intents.all()
client = MyClient(intents=intents)
@client.tree.command()
async def test (interaction: discord.Interaction, name: str, age: int):
await interaction.response.send_message(f"{name}'s age is {age}")
@client.event
async def on_ready():
print(f"Bot is ready!")
my_guild = discord.Object(556053478812942366)
let's add this thing in a variable
url=['link'] #this is the output
full_output=url.replace("['']", "")
thank you brother
hmm so
i do this before the command?
imagesz = [
"https://cdn.discordapp.com/attachments/1019185962196140042/1019186447913332756/IMG_6764.png",
"https://cdn.discordapp.com/attachments/1019185962196140042/1019186449934983249/IMG_6759.png",
"https://cdn.discordapp.com/attachments/1019185962196140042/1019186450736091207/IMG_6762.png",
"https://cdn.discordapp.com/attachments/1019185962196140042/1019186514971869215/IMG_6778.png",
"https://cdn.discordapp.com/attachments/1019185962196140042/1019186448852856853/IMG_6754.png",
"https://cdn.discordapp.com/attachments/1019185962196140042/1019307993910759474/IMG_6818.png",
"https://cdn.discordapp.com/attachments/1019185962196140042/1019186514044932167/IMG_6769.png",
]
@client.slash_command(guild_ids=[1019184533117096006])
async def randomtest(interaction = Interaction):
await interaction.response.send_message(random.choices(imagesz, weights=(70,70,60,50,50,50,10), k=1))
😅
image=random.choices(imagesz, weights=(.....), K=1)
full_image=image.replace("['']", "")
await interaction.response.send_message(full_image)
@tropic estuary try
trying
File "e:\codes ig\shakm bot all\backup\bot.py", line 53, in randomtest
full_image=image.replace("['']", "")
AttributeError: 'list' object has no attribute 'replace'
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'replace'
wait.
Oh nvm wait
It will be
await interaction.response.send_message(image[0])
Remove full_image variable
members = await guild.members(limit=250).flatten()```
is this correct?
trying to fetch members
how to make avatar command?
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
@tropic estuary try this, i didn't notice it was a list 💀
YOOOO
IT WORKED, TYSM MAN
wlc :]
legit hero right there
xd
@slate swan
any idea how to blacklist someone from getting a role?
the ex if u put status u get a role.. but any way to make someone not get the role?
Make a database some sort of
If u don't know anything about data base just use txt file
can u use js?
Put some blacklisted member id in the txt file
U mean json
Not recommended
yea yea
I said so xd
i mixed those up
If you don't know anything about databases, better get to learning!
Using txt is for newbies xd
Oh xd
and how do i link them?
then in ur event check for if after.id in thst txt file
@slate swan how do i automatically get the guild id? any thing u can do?
If it's then it will not give him role
When bot joins a server?
yep
so i dont have to get the guild id everytime
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
do i do intents.guilds = true?
before:
async def on_presence_update(before, after):
role_id = ROLE ID
role = get(before.guild.roles, id=role_id)
if 'STATUS' in str(before.activities):
if 'STATUS' in str(after.activities):
pass
else:
await after.remove_roles(role)
if 'STATUS' in str(after.activities):
await after.add_roles(role)```
Yea?
and i dont understand how should it look after..
check only example
with open('blaclist.txt', 'r') as f:
f=f.readlines()
if str(after.id) in f:
return
Kinda like dat
so
async def on_presence_update(before, after):
role_id = ROLE ID
role = get(before.guild.roles, id=role_id)
if 'STATUS' in str(before.activities):
if 'STATUS' in str(after.activities):
pass
else:
await after.remove_roles(role)
if 'STATUS' in str(after.activities):
await after.add_roles(role)
with open('blaclist.txt', 'r') as f:
f=f.readlines()
if str(after.id) in f:
return```
like this?
I edited my code
me too
Also u need to create a 'blacklist.txt' file
yeah i know i did
so is that script good?
@slate swan
Yes
ok bro tysm
In this code u have to put blacklisted member id manually in that file
There is a way to do it without manual
Manually*
For now try manually
the ex
123456789
0987654321```
etc
in the blacklist.txt?
Yes
ok tysm bro
Also it's txt file recommending database tho
f=f.readlines()
^
IndentationError: unindent does not match any outer indentation level
@slate swan
Gimme new ckde
Code
ok 1 sec
async def on_presence_update(before, after):
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if 'status' in str(before.activities):
if 'status' in str(after.activities):
pass
else:
await after.remove_roles(role)
if 'status' in str(after.activities):
await after.add_roles(role)
with open('blacklist-bronze.txt', 'r') as f:
f=f.readlines()
if str(after.id) in f:
return```
this is new code
rolesList = ctx.guild.roles
rolesList.reverse()```
why does reverse doesnt work here?
@slate swan
why is my error handler not working ?
@commands.Cog.listener()
async def on_command_error(self, error):
if isinstance(error, commands.MissingPermissions):
embed = discord.Embed(description = 'not admin', colour=0xF1C40F)
await self.ctx.send(embed=embed)
Sorry got a phone call
np np
async def on_presence_update(before, after):
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if 'status' in str(before.activities):
if 'status' in str(after.activities):
pass
else:
await after.remove_roles(role)
if 'status' in str(after.activities):
await after.add_roles(role)
with open('blacklist-bronze.txt', 'r') as f:
f=f.readlines()
if str(after.id) in f:
return```
anyone?
Yes it has
sends roles list in low to high hierarchy
yea i can
Ok then send me output
!e
mylist = list(range(10))
print(mylist)
print(list(reversed(mylist)))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
002 | [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
!d reversed
reversed(seq)```
Return a reverse [iterator](https://docs.python.org/3/glossary.html#term-iterator). *seq* must be an object which has a `__reversed__()` method or supports the sequence protocol (the `__len__()` method and the `__getitem__()` method with integer arguments starting at `0`).
Yep going to say it needs to conv to list
SequenceProxy(dict_values([<Role id=831580898352562176 name='EC-RPG Owner'>, <Role id=831794149346902026 name='Vice Godfather'>, <Role id=831793854797709312 name='Hitman'>, <Role id=831792982935339030 name='Dock Worker'>, <Role id=930324354754027570 name='Rat'>, <Role id=831793815022731275 name='Criminal'>, <Role id=831829132811829268 name='Cow'>, <Role id=831793496158896158 name='Firefighter'>, <Role id=831580168325038090 name='Cock Lover'>, <Role id=827054767883812904 name='BankTime'>, <Role id=831794052580114433 name='Vice Mayor'>, <Role id=895036506962559028 name='MecHaNiC'>, <Role id=831792861157523457 name='Trucker'>, <Role id=831793892369498152 name='Assassin'>, <Role id=831792769201733642 name='Journalist'>, <Role id=870689243796762634 name='I ♥️ Camels'>, <Role id=831793389641007114 name='Police Officer'>, <Role id=831793971411943434 name='Mayor'>, <Role id=1045296323190079562 name='Footballnation'>, <Role id=831793722977943592 name='FBI Agent'>, <Role id=898966739428196393 name='Bots'>, <Role id=831793183695831050 name='Pilot'>, <Role id=831578719901843466 name="Owner of Shyam's love">, <Role id=831948426127081522 name='[KSV]'>, <Role id=831785678206402630 name='Mechanic'>, <Role id=854374785118765097 name='DJ'>, <Role id=833754314869964891 name='YouTube'>, <Role id=833265847547068416 name='Muted'>```
Or just slice the list
This is not list
output should be like this but in revered order
i got no error thx
for role in ctx.guild.roles:
I
Cool
Or just use reversed method on the guild.roles 🐈
for role in reversed(ctx.guild.roles):
...
Kind of genius
ok thx
^^^^^
SyntaxError: invalid syntax```
@slate swan
Do you have basic Python knowledge
Remove str 💀
yeah i know 💀
cd
im stupid just wanted to say that i fixed
still getting the role..
Did u put correct member id?
yup
Ahh then
This doesn't look #discord-bots related 🐈
@bot.event
async def on_presence_update(before, after):
with open('blacklist-bronze.txt', 'r') as f: f=f.readlines()
if str(after.id) in f:
return
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if 'status' in str(before.activities):
if 'status' in str(after.activities):
pass
else:
await after.remove_roles(role)
if 'status' in str(after.activities):
await after.add_roles(role)
you have any ideea how to solve it?
do I see spoonfeeding
both of you
Ohk 💀💀
!e print(str(["apple", "banana"]))
@cold sonnet :white_check_mark: Your 3.11 eval job has completed with return code 0.
['apple', 'banana']
@cold sonnet :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
how do i get the ban list ?
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
not working as in you're not getting a role?
no
its supposed to not give me the role bcs im blacklisted
but im still getting it
put it
i can't do copy paste it's supposed to work but i don't think you have any idea what i'm trying to do
The readlines return the lines with \n at the end
I don't know how to properly explain
async def bannedlist(self, ctx):
banList = ""
async for user in self.guild.bans(limit=150):
print(user.name)```
like this?
like this it's just "id" in ["id\n"] which are not the same
async def on_presence_update(before, after):
with open('blacklist-bronze.txt', 'r') as f: f=f.readlines()
if after.id in f:
return
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if '4rr3e' in str(before.activities):
if 'rr3swew' in str(after.activities):
pass
else:
await after.remove_roles(role)
if '4t3sw' in str(after.activities):
await after.add_roles(role)``` this is script (that isnt the real status)
i got the ids like this
but if i put them all in the same line with ; or , beetween them it wiill work?
yeah that would print every banned user
I would suggest you to use read and split it. So you don't get this problem
u talkin to me right?
Who else
but it doesnt
or convert readlines to str lmao
is self.guild defined?
Just ask about it 🐈
OH SHIT FORGOT
f=f.read().split()
async def bannedlist(self, ctx):
async for entry in self.guild.bans(limit=150):
print(entry.user, entry.reason)```
@slate swan
.
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
yeah...
i did same
but it did print entry objects didn't it
it doesnt print anything
Did u tried running command?
how did you define self.guild?
wdym running command
and where
wydm ?
in the async?
Ask the question or about the problems you have, people will try to help you
like for guild in self.bot.guilds?
self.guild = ctx.guild?
I see you didn't do that
are you in a cog?
you probably are since you're using self
i want to put this```py
bot.http_session: ClientSession = ClientSession()
async with bot.http_session.get(...) as resp:
print("Content-type:", resp.headers['content-type'])
in this codepy
if value := self.children[0].value:
if not re.match(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", value):
await interaction.response.send_message(content="Url Invalid")
return
else:
for url in self.children[0].value:
if url.content_type in ('image/jpeg', 'image/jpg', 'image/png'):
embed.set_image(url=self.children[0].value)```
Where exactly
I want to point to an image with aiohttp
Yeah, but where do you want it to be
when i am trying to add more then one reward it doesnt work, works only if i add one
https://paste.pythondiscord.com/uqalanenat
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 655, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 1524, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.```
here:py async with session.head(self.children[0].value) as resp: for url in self.children[0].value: if url.content_type in ('image/jpeg', 'image/jpg', 'image/png'): embed.set_image(url=self.children[0].value)
Why are you iterating over a string?
so it should be under else in the code i just want it to link to an image with aiohttp if you know what i mean
!e
for url in "https://acool.url":
print(url)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | h
002 | t
003 | t
004 | p
005 | s
006 | :
007 | /
008 | /
009 | a
010 | c
011 | o
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ogikowipud.txt?noredirect
the url i get from self.children[0].value
i just want to link it to a image with aiohttp
.value return a string
Anyways 2, you can just put the async with session.head(self.children[0].value) as resp: right after the else statement
like this
async with session.head(self.children[0].value) as resp:
if resp.headers["Content-Type"] in ('image/jpeg', 'image/jpg', 'image/png'):
embed.set_image(url=self.children[0].value)```
You don't need
for url in self.children[0].value:
line. You can just check if the content-type is in the image types tuple
async def bannedlist(self, ctx):
banList = ""
async for entry in ctx.guild.bans():
if not entry:
embed = discord.Embed(description = "Ban list is empty.", color = discord.Colour.gold())
await ctx.send(embed = embed)
print("no bans")
else:
print("bans")
print(entry)
for ban in entry:
banList += f"__**Name:**__ {entry.name}, __**ID:**__ {entry.id}\n"```
what am i doing wrong here?
Like
if resp.headers["Content-Type"] in (...):
ah
Any exceptions
if resp.headers["Content-Type"] in ('image/jpeg', 'image/jpg', 'image/png'):```
Correct
idk, nothing comes up
Did you call the function
thanks
i am not raising any errors for now ;3 have tor rewrite it for 2.0 ;3
just checked :3
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
if message.channel.id == 1011882292253294642 or message.channel.id == 1011881268285280316:
for emb in message.embeds:
chat = discord.utils.get(self.get_all_channels(), id=1047707576315420672)
print(chat)
print(chat.name)
embed = discord.Embed(title=f"[Ownerless Group]({emb.url})")
embed.add_field(name="id", value=emb.fields[0])
embed.add_field(name="name", value=emb.fields[1])
embed.add_field(name="Members", value=emb.fields[2])
print("1")
await chat.send(embed=embed)
print("4")```
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
discordpy-self is a selfbot library
There is no discordpy-self there wtf?
I see
Thats the name of the project because I copied from github but im making a bot
Thats why I was like bro what this is not selfbot lol
was there any change in on_command_error in 2.0?
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandInvokeError):
error = error.original
return await ctx.send(error)```
i have this previous error handler
🤡
what exception should i check for?
That library is using the user API, not the bot. So I'm very sure that it would throw an error if you tried to login using a bot token 
Nope try it
still getting the role 😭
code looks liike this @slate swan
I defined chat as a channel, how do I make a webhook send a message in that specific chat?
The after.id is an int
webhook.chat.send(embed=embed)?
Convert it to a string first
@slate swan
oh
user API?
Anyone knows?
await (await channel.create_webhook()).send(embed=embed)
i think
if yes im getting this
@naive briarit an command invoke error
str(after.id) 
U need parentheses
Most issues im seeing here seem like issues relating to knowledge about basic python
amen
how do i get the name and id only for a banentry?
!d discord.BanEntry.user
The user’s username.
The user’s unique ID.
How do I setup autocomplete for when user's trying to type something in a paremeter for slash commands?
I've seen some bot's doing this
thanks all
!d discord.app_commands.autocomplete
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.11)"), or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.11)") values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete "discord.app_commands.Command.autocomplete") documentation.
Example:
There's an example in the docs
Thank you so much!
can i somehow make so if it gets lable then the option gets created otherwise it gets ignored
banList = ""
for ban in entry:
print(ban)
print(entry)
banList += f"__**Name:**__ {ban.user.name}, __**ID:**__ {ban.user.id}\n"```
doing like this but raises attribute error
Hello which module is better to make my requests faster in dpy?
I have webhook defined as the link to the webhook, how do I make the webhook send link to a specific channel, I defined the channel as chat, so webhook.chat.send(embed=embed)?
what is the best package to make own server's bot using python?
I don't know what you mean
Hikari or discord.py, both are great discord API wrapper library
Nobody knows?
requests as in http requests?
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
#prefix for commands
rijalbot = commands.Bot(command_prefix='!',intents=intents)
#commands
@rijalbot.command()
async def rijalhelp(ctx):
await ctx.send("")
@rijalbot.event
async def on_ready():
print("RijalBot online")
await rijalbot.change_presence(activity=discord.Game('!rijal'))
TOKEN = ''
rijalbot.run(TOKEN)```
Im running this, to get a custom status, but this is the traceback I get Traceback (most recent call last):
File "C:\Users\intel\Desktop\rijalbot\venv\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\intel\Desktop\rijalbot\main.py", line 17, in on_ready
await rijalbot.change_presence(activity=rijalbot.Game('Sea of Thieves'))
AttributeError: 'Bot' object has no attribute 'Game'
Also ignore the "sea of thieves" on the traceback, this was before i edited the game message
!d discord.Activity
class discord.Activity(**kwargs)```
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
• [`Game`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Game "discord.Game")
• [`Streaming`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Streaming "discord.Streaming")
@commands.check_any(commands.is_owner(), commands.has_permissions(manage_messages = True))
@commands.command(help = "Blacklist a user from the bot's commands.\n*PERM_NEEDED = MANAGE_MESSAGES*", aliases = ['bl'])
async def blacklist(self, ctx, option, member: discord.Member):
print("invoked")
guild = str(ctx.guild.id)
print("1")
try:
print("try")
blackList = self.blackList[guild]
print("tryafter")
except KeyError:
print(KeyError)
blackList = []```
why is this code not printing?
import discord, asyncio
from discord.ext import commands
bot = commands.Bot(command_prefix="!", help_command=None, intents=discord.Intents.all())
async def send():
print(bot.is_ready())
while True:
if bot.is_ready() == True:
break
channel = bot.get_channel(1038147142134550578)
await channel.send(content="yee")
asyncio.run(send)
bot.run("")
```anyone know how to fix
How do I make my bot repeat what I say (on command)? For example, if I say “!text Im the best bot”, my discord bot will reply “Im the best bot”
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
Why does this error even happen dude
I'm answering within 3 seconds
and it still says unknown interaction
where is the interaction coming from? can you show your code?
@bot.command()
async def say(ctx, text)
await ctx.send(text)
?
anyone?
:
it would just say the first arg
do you have an on_message or an on_command_error handler? not printing would suggest the command wasn't able to run, either because your bot couldnt see/read the message or it silently failed to run the command
class NewCode(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="ساخت کد یک بار مصرف", style=discord.ButtonStyle.green, emoji="✉",custom_id="newcdbut")
async def button_callback(self,button,interaction):
has = False
for role in interaction.user.roles:
if role.id == ROLE_ID:
has = True
if interaction.user.id in OP_LIST or interaction.user in interaction.message.mentions or has == True:
def generateCode():
newCode = []
for i in range (5):
newCode.append(str(random.randint(0,9)))
newCode = "".join(newCode)
return newCode
result = generateCode()
with open("oncecodes.json","r") as file:
data = json.load(file)
while result in data:
result = generateCode()
await interaction.response.send_message(content=f"{interaction.user.mention}",embed=embed,ephemeral=True)
data[result] = interaction.channel.category.id
with open("oncecodes.json","w") as file:
json.dump(data,file)
await delete_after(result)
else :
await interaction.response.send_message(content=f"{interaction.user.mention}",embed=embed,ephemeral=True)
Had to delete some lines so i could send the code
!paste if its that long
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.
i do, let me remove them and try
what version of discord.py did you install?
nah just deleted the embed parts
me? i use pycord
seems they havent switched button and interaction around like dpy
Hmm maybe my version is outdated
lemme check
yes it is
but how is updating the pycord going to help me
i didnt suggest that
is it a bug?
i was just pointing out a difference
oops
if you were using d.py 2.0 alpha then it'd be a bit concerning
there's quite a bit going on in that callback, have you tried putting print statements to see what's happening?
removed them still nothing
yes, and sometimes it just works, sometimes says unknown interaction
its just random
You probably took too long to respond to the interaction
but its the same code, why does it work sometimes and sometimes dont
what intents did you pass to your bot constructor?
all
and other commands work fine, right
You're generating random code and it has a chance to be duplicated and take longer to find the one that isn't duplicated
yes
how can I make it so that when
async def on_ready():
happens it will go through all members and add a role to them?
@ad.event
async def on_ready():
admsg = pyfiglet.figlet_format("| ADVERTISING |")
sync = await ad.tree.sync()
os.system('clear')
print(Fore.MAGENTA + f"\nIm online.\nUser: {ad.user}.\nSynced {len(sync)} commands.\n" + Fore.RED + f"{admsg}")
guild = ad.get_guild(1048657638369525811)
role = guild.get_role(1048657918347706438)
for member in list(guild.members):
await member.add_roles_role
your interaction responses seem to be fine by themselves so the rest of your logic might be what's slowing it down, but i cant guess which part so you'll need to make further measurements (is the if-statement slow? is generating the unique code slow? etc.)
maybe opening / closing the files is what makes it slow
can you host a discord bot on a raspberry pi
is there any other method in your cog named blacklist? what output do you get when you print bot.get_command('blacklist') after loading the cog?
there isnt
dk about 2nd one
nvm, worked. i am dumb lol
Im gettign this error, NameError: name 'discord' is not defined
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
#prefix for commands
rijalbot = commands.Bot(command_prefix='!',intents=intents,activity=discord.Game(name="!rijal"))
#commands
@rijalbot.command()
async def rijalhelp(ctx):
await ctx.send(".")
@rijalbot.event
async def on_ready():
print("RijalBot online")
TOKEN = ''
rijalbot.run(TOKEN)```
You did not define discord
Wdym?
I mean exactly what I said
You really need basic knowledge of Python to start making Discord bots
how do i find if a thread already exists in a channel (using nextcord)?
!d discord.TextChannel.threads
property threads```
Returns all the threads that you can see.
New in version 2.0.
You can check if the thread object is in this list or not
yeah but it returns a funky list
like it returns a list with the ID, name, parent, etc. in the same object so idk how to check the name only
why do I keep getting rate limited when nothing sus is going on?
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.
You keep connecting or doing something too fast
is channel.threads.name a thing?
threads returns a list of thread channel objects
you might wanna access a single element
You can check them by name using any method or generator / list comprehension
The thread name.
you can use discord.utils.get to get the thread object with a specified name
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
ngl I prefer filter to this method tho
yeah but like:
thread = nextcord.Thread
thread_name = f"{user_name}'s RPG"
print(thread)
print(channel.threads)
print(thread_name)
if thread_name not in channel.threads:
await channel.create_thread(
name=f"{user_name}'s RPG",
)
await thread.send(f"{ctx.author.mention}"
doesn't work
I want it to create a thread, add the command user in it but ONLY if a thread with the name (defined in thread_name) does not exist
u r checking for a string in a list of discord.Thread objects
yeah i saw that just now also
use utils.get and check if it is None and if it is then create a thread
so like nextcord.utils.get(channel.threads, name=<name>)
yup
Okay! Lemme try it out
Ah yes, I messed up the assigning of the thread variable
@maiden fable Thx! it works!
so I have a spam detector but how can I make it delete 5 of the spammers recent messages?
anywhere to start from?
sorry to bother, but it kinda does work, except it creates another thread even though there already is one.
Then the variable isn't defined
Can you share yr code?
thread = nextcord.utils.get(channel.threads, name=f"{user_name}'s RPG")
print(thread)
print(channel.threads)
print(thread_name)
if thread == None:
thread = await channel.create_thread(
name=f"{user_name}'s RPG",
)
print(thread)
print(channel.threads)
await thread.send(f"{ctx.author.mention}")
it prints out the following:
None
[<Thread id=1048689495446392962 name="Snufie6356's RPG" parent=rpg owner_id=1033399460975362139 locked=False archived=False>]
Snufie#6356's RPG
Snufie6356's RPG
[<Thread id=1048689495446392962 name="Snufie6356's RPG" parent=rpg owner_id=1033399460975362139 locked=False archived=False>, <Thread id=1048689853707067482 name="Snufie6356's RPG" parent=rpg owner_id=1033399460975362139 locked=False archived=False>]
Snufie#6356's RPG
Thanks
np
what is thread_name?
thread_name = f"{user_name}'s RPG"
Oh yea lol
owner id
Nice catch
Hm then nvm
!d str.strip
str.strip([chars])```
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or `None`, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped:
```py
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
``` The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end. For example:
Is the bot private or public?
private
property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.name "discord.User.name")
yeah but it's going to be public when it's done, if ever
Ah okay
For that btw if u want a safer method I think u should maintain a DB with the user's ID and the thread ID. This is safer because in case the user changes their name or tag, then it will create another thread
good one
i'll look into that for sure, it sounds a lot better than what I am doing now XD
Haha cool
why its not working
ctx.guild
thanls
Traceback (most recent call last):
File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 94, in purge
messages = await ad.channel.history(limit=amount).flatten()
AttributeError: 'async_generator' object has no attribute 'flatten'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'
messages = await ad.channel.history(limit=amount).flatten()
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
Look at the example
async for messages in ad.channel.history(limit=amount)
Traceback (most recent call last):
File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 95, in purge
for message in messages:
TypeError: 'Message' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: TypeError: 'Message' object is not iterable
async for messages in ad.channel.history(limit=amount):
for message in messages:
if str(message.author) in count_members:
count_members[str(message.author)] += 1
else:
count_members[str(message.author)] = 1
Traceback (most recent call last):
File "D:\python\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "d:\Nothing\main.py", line 241, in callback
await interaction.response.send_message(f"Given the role {role.mention}", ephemeral = True)
File "D:\python\lib\site-packages\discord\interactions.py", line 769, in send_message
await adapter.create_interaction_response(
File "D:\python\lib\site-packages\discord\webhook\async_.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
i am confused
line 241 is perfect i think
@naive briar can help?
You took too long to respond
!d discord.InteractionResponse.defer - use this coroutine if you need to take over 3s to respond
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...
its working fine for 1st and second option
also its removing and adding role for 3rd one but i cant see the response
i made these color roles with discord.py but they stop working after few mins
can someone help?
Is this correct to send an embed to a specific channel id?
cchannel = await self.bot.get_channel(id=flight_channel_id)
await cchannel.send(embed=embed)```
yes
ok ty
no, you don't await get_channel and id is a positional argument
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
yea found out
nice
Im trynna get the group id, name and amt of members out of this embed and send in another embed
But this is the output
embed.add_field(name="id", value=emb.fields[0])
embed.add_field(name="name", value=emb.fields[1])
embed.add_field(name="Members", value=emb.fields[2])``` this is code
My guess is that link is in the description, not the title
But what about those fields
when getting fields from an embed, it gets an embed field, or looks like an EmbedProxy object. make sure to get the value of said embeds
emb.fields[0].value
And to fix the link?
put it in the description
Cause it gets the link correctly
The problem is that it sends [ownerless][https:jajajjsisisjwj.com)
For example^
And not ownerless with the link when u click the word
Like I said, put it in the description, not the title
Ok
discord.Embed(description=f"[Ownerless Group]({emb.url})")
Ok
Wym by that
discord.Embed(title=f"Ownerless Group", url=emb.url)
What that would do?
I believe it makes the title a link
Ok
hello im trying to make a voice channel recorder with multiple recordings (one per speaker) but i cant seem to find ANY info on it can anyone point me in the right direction
This doesn't sound like something discord would like..
discord.py doesn't support voice recieve anyway
pycord does
Interesting
We don't provide help on this topic.
I've never seen it but ok
Because it's unethical and to mention privacy.
its not unethical to record a podcast in your vc
It's been discussed many times, contact @novel apex if you disagree. And get clearance from a staff member.
If it's to only record one voice I suggest using 3th party software. And btw py-cord is a very bad example on discord.py coding.
the goal is to build a multi channel (as in each speaker is its own channel of audio) recording bot to be able to mix and master each individual audio output
ive seen my boss do it with pycord in like 10 mins
but he wont tell me how bc i need to learn it
but there seems to be 0 info
Because of it's unethical nature. Because of legal issues Discord.py doesn't support it natively.
Considering how many extra code would be needed to make it acceptable. Including every countries and states laws.
this seems like a gross misunderstanding of almost everything mentioned
You want to record audio in a voice channel.
yeah in my private discord
Then we're on one line, doesn't matter if it's private or not.
theres 0 ethical concerns beyond the concerns that can be levied against any discord bot functionality
abuse is abuse regardless of the tool
Agreed, so if I say it's unethical and you disagree we're having a debate if something is "abuse" or not. But as mentioned in my previous message you don't need to convince me. Convince @novel apex .
It's not silly, what's silly is the amount of people that I've helped, with good intentions and to later see they use it for something unethical.
Hence why most people that help here are quite strict about it.
We don't care what the context is or the situation
Recording at all is just unethical
meow
And I've given everyone that asks about recording the same answer. If you disagree then talk to staff.
But also, why??
!xy
xy-problem
The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.
Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.
For more information and examples, see http://xyproblem.info/
i host a debate tournament through discord for streamers and youtubers and i want to make this to record the audio for later editing for spotify uploads and as a portfolio piece for my resume
even bots like mee6 have this feature
its extremely common
mee6 lmfao
You keep coming up with very bad examples I might add.
i dont use it but its one of the most used bots
mee6 also did music for 4 years and NFT's
an easier way would be using google meet instead of discord 💃
I think it's still doing nfts
but then i dont get a resume piece
also music bots on discord are wonderful
youre a loser if you think otherwise
and ban-able
except for ones designed by the music provider itself
SoundCloud bot for instance
yeah but bannable bot or not its still a cool thing to create and a great thing to have
Some sites are also copyright free.
Do keep it respectful.
I agree, sadly there are limits.
The whole point of banning music bots it to support creators. Why are you so against that?
Forcing people to watch on youtube or spotify give creators more money.
Let it be ads or paid subscription.
that they actually deserve :p
Besides there also is a youtube activity that plays music for you.
MFW when spotify does 43 hundred-thousandths of a dollar per stream
Pretty under paid imo
the [0] part is being done before await
i think that does work ya but you should be separating it out into another line to make it more clear
wait no
i used to do that before
but it still doesnt work
actually i dont need [0]
does it work without the [0] part now?
yes
then created = [] if the table is empty
what is this
Hey
hi
can someone help me with this?
role = discord.utils.get(interaction.guild.roles, name="🎄 Christmas 2022")
does this get the id
try it?
can't rn
!d discord.utils.get
tf
emoji can be inside role name?
ye
INSERT INTO table VALUES (1, 2, …)
this is the table
oo
Need the VALUES part
jesus ok
I think that the arguments are not passed as a tuple but as their own argument
((arg1, arg2, arg3)) should be (arg1, arg2, arg3)
like this?
Yeah
I made some drop down menus but they stop working after few mins of not using them, how can I make them permanent
Is it cuz of my hosting or something?
thats normal, set timeout to None if you want to ignore this behaviour
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
the timeout kwarg
