#discord-bots
1 messages ยท Page 277 of 1
vscode terminal?
Bro Asher take water
files rest within folders not within files ๐ฟ
Bro u ask tomorrow
But you could.
technically yeah but would u?
Isn't a zip file technically just one file?
Pandab
u cant make edits
niti
Bro anyone solve my problem
with unzipping it
Just unzip an rezip it everytime.
totally
What unzip vro
What?
How to insert return these .replace(r"\x", "") in re.sub(r'src=\s?"//(.)?"', r'src="https://0.0.0.1/"', html_text) insert in these line
ur vscode terminal has same path as your main terminal unless u in a workspace or u opened vscode from ur terminal path what i am saying is navigate to your python file folder and make sure the path to this folder is what is shown in your terminal as well
I assume the r'src is just gibberish to what you want to achieve?
Bro open cmd in your folder
exactly
im so dumb
Remove extra space from scrapping text showing /x
No bro
i am gonna go sleep gn guys
Before or after the \x?
gn
Yes
gn
Lol
Yes bro both side
What are you guys even doing
a single space on both size or uknown amount?
@buoyant quail how do I update button emoji on after interaction?
You want to remove the text that's overlapping?
Click on button
Yessss bro
Very nice answer but i don't need answers from you. Thanks.
Could you show the code of a sentince that has that weird overlapping?
I believe you can just do button.emoji = ...
And then you need to edit the message ofc
Lemme show you my code
def slugify(value: str, allow_unicode: bool = False) -> str:
"""
slugify the names of files
:param value: string to be slugify
:type value: str
:param allow_unicode: allow unicode
:type allow_unicode: bool
:return: string after slugify
:rtype: str
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize('NFKC', value)
else:
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value.lower())
return re.sub(r'[-\s]+', '-', value).strip('-_')
if player.is_playing():
button.emoji = '<1134067079180464188>'
await player.pause()
await interaction.edit_original_response(view=self)
if player.is_paused():
button.emoji = '<1134067069848133684>'
await interaction.edit_original_response(view=self)
@buoyant quail
He has eyes ig
You have two < in the beginning
What u making bro
a bot?
Thanks but I meant like the raw string.
That's because i copy pasted
So there is only one?
errors?
Which type of these string
The one that contains weird overlapping.
No errors just button isn't working
It's showing This interaction failed
How I know bro 1k line code
You wrote it you should know
Are you sure that one of these conditions is true?
CTRL+F on some words that are close with the overlapping text.
Ok
I used them as docs said ๐
But you have a point
Add prints to check
class it
Tf?
class PauseButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
#rest of code```
You're out of context ig
how?
I have a class but issue is with that specific button
Yeah and search the overlapping text then.
Or just give me the whole raw text if you can't find it.
oh ok
@buoyant quail it printed
Try interaction.response.edit_message
I am not sure about edit_original_response
yeah
examples/views/counter.py lines 35 to 36
# Make sure to update the message with our updated selves
await interaction.response.edit_message(view=self)```

or do on the command message = interaction.original_response()
then do message.edit(content=)
It will take two api calls
I tried interaction.edit_message
And still it showed interaction failed and printed too
Do you have error handlers?
Yes
I use it
Show them
@cloud dawn
Wait I should try it inside try except
Sorry disturbing bro
Does this include the site data? Because that's what I'm after.
Doesn't look like it I'd need to run this code.
Many files
But these is scrapping file
Which scrap answer
I just need one containing the overlapping issue.
'interaction' object has no attribute edit_message @buoyant quail
Yes these one
Which I send
Where did you get it
why not this then?
It was not in yours and in mine codes
i use it
Oh the code is the scraped file?
Wait
ans it works
Here
And what i showed you? :p
.
response
Lol, confusion lol
Worked now thanks @buoyant quail
Oh then not confused
Beautiful soup
I can't do anything with this code I need the response from the code.
I don't want to run this code just to know what text you get.
I have bot who scrap answer and and send me
But in some answer
Show isuee which I show in image
I know but you just sent me code. I can't fix the issue if I don't have the raw text from the response.
Hey I have a purge command that is up and running that however works with a prefix, and I'd like it to be a useable slash command, but cannot figure out how to do it for the life of me... Here's my code :
@client.command()
async def purge(ctx, amount: int):
if amount > 1000:
await ctx.send(f"Too many messages to delete ({amount}/1000)")
else:
count_members = {}
async for message in ctx.channel.history(limit=amount):
if str(message.author) in count_members:
count_members[str(message.author)] += 1
else:
count_members[str(message.author)] = 1
new_string = []
deleted_messages = 0
for author, message_deleted in count_members.items():
new_string.append(f"**{author}**: {message_deleted}")
deleted_messages += message_deleted
final_string = "\n".join(new_string)
await ctx.channel.purge(limit=amount + 1)
embedVar = discord.Embed(title=f"{deleted_messages} messages were removed", description="", color=0x00ff00)
embedVar.add_field(name="Deleted Messages", value=final_string, inline=False)
embed_message = await ctx.send(embed=embedVar)
await asyncio.sleep(2)
await embed_message.delete()```
If someone could help me out that would be awesome
Ok bro I try to fix myself because there many files attached I not able to send you
It's like giving someone a broken computer and not telling them what the issue is.
Well you're in luck since I just need one sentence with the overlapping text in it lol
Ok wait I find
https://github.com/Rapptz/discord.py/tree/master/examples/app_commands
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
examples with some explanations
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
<3
Just inspect element on a sentence that has overlapping text.
ok
Anything works.
<mtext>9 rad/s\xa0</mtext>
Ah makes sense it renders weird.
Delete the whole <mtext>9 rad/s\xa0</mtext> or just \xa0?
just \xao
actual answer is 9rad/s
bro
def _get_response_text(self, url: str, headers: dict = None, extra_headers: dict = None,
expected_status: tuple = (200,), note: str = None,
error_note: str = "Error in request", raise_exception=False) -> str:
"""
text response from web
:return: Text response from web
:rtype: str
"""
logging.debug(msg=f'::getting response from url: {url}')
response = self._web_response(url=url, headers=headers, extra_headers=extra_headers,
expected_status=expected_status, note=note,
error_note=error_note, raise_exception=raise_exception)
logging.info(msg=f'::response status code: {response.status_code}')
if response.status_code not in expected_status:
raise Exception(f'Expected status code {expected_status} but got {response.status_code}\n{error_note}')
return response.text.replace("\xa0", "")
Just replace that function.
ok
return response.text.replace("\xa0", "")
^
IndentationError: unindent does not match any outer indentation level
C:\Users\HP WORLD\Desktop\d>return response.text.replace("\xa0", "")
'return' is not recognized as an internal or external command,
operable program or batch file.
C:\Users\HP WORLD\Desktop\d> ^
More? IndentationError: unindent does not match any outer indentation level
'IndentationError:' is not recognized as an internal or external command,
operable program or batch file.
showing error
Did you copy it correctly?
yes
Can you send a screenshot?
ok
bro'
work
/xao
not showing
but still overlapping
turret is zero.\na_barrel_turret = 0 m/s^2\n\n
and these \n\n
show
@cloud dawn bro
get removed
/xao
see here
are we supposed to click on this suspicious link?
It's because you scraped it.
I see but it's overlapped because you don't have mjx-assistive-mml
and for these
It's not rendered correctly
I'm gonna go to sleep lol
It's a render issue folk over at #web-development are better with this.
ok u help me lot bro
Just tell them that mjx-assistive-mml tag isn't rendering correctly.
thank you so much
Lots of reading and a few tutorials later, I got a code that doesn't spam errors
But the purge command just doesn't work :)
@bot.tree.command(name="purge")
@app_commands.describe(message_number='How many messages would you like to delete?')
async def purge(ctx: discord.Interaction, message_number: int):
if message_number > 1000:
await ctx.response.send_message(f"Too many messages to delete ({message_number}/1000)")
else:
count_members = {}
async for message in ctx.channel.history(limit=message_number):
if str(message.author) in count_members:
count_members[str(message.author)] += 1
else:
count_members[str(message.author)] = 1
new_string = []
deleted_messages = 0
for author, message_deleted in count_members.items():
new_string.append(f"**{author}**: {message_deleted}")
deleted_messages += message_deleted
final_string = "\n".join(new_string)
deleted = await ctx.channel.purge(limit=message_number)
embedVar = discord.Embed(title=f"{len(deleted)} messages were removed", description="", color=0x00ff00)
embedVar.add_field(name="Deleted Messages", value=final_string, inline=False)
embed_message = await ctx.send(embed=embedVar)
await asyncio.sleep(2)
await embed_message.delete()```
I'm not sure if this might affect it but I set this part at the beginning of my code to be client.event and not bot.event
async def on_ready():
await tree.sync(guild=discord.Object(id=guildid))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=f'{status_message}', status=discord.Status.dnd))
print(f"Logged in as {client.user}")
channel = client.get_channel(status_channel)
async for message in channel.history(limit=1):
global msg_id
msg_id = message.id
await asyncio.gather(update())
#got this part off a tutorial, I don't understand the details but I understand that it's what syncs the command between the bot and discord
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)```
Part of the code was made by someone else who used @client.event it's used to interract with a server and is beyond my current scope of understanding, I'm just scared that if I change the wrong shit it will all just break ?
You shouldn't be making any API calls in on_ready
Where do you think I should put it
Make a text command to sync your app commands
mind if I DM you
you can also override Client.setup_hook to do async prep work but iirc that gets called before your bot is connected to the gateway so you might get errors or deadlocking
Failed to build mjx grpcio
ERROR: Could not build wheels for mjx, grpcio, which is required to install pyproject.toml-based projects
how to fix
Not a clue, try make a #1035199133436354600 post or googling it
check ur DMs real quick
can someone help me, I made a command, with buttons, but when I click them it says "interaction" has no attribute "send"

interaction.response.send_message('Clicked', ephemeral=True)
is there a better python discord API wrapper out there than discord.py?
Every is good just preference
"Better" in what regard?
eh i phrased that wrong. so im using a very old version of discord.py because i had to go on a forced leave. so im returning and need to rewrite the whole bot because nothing is the same. so at this point im wondering if there's anything i could try to pick up instead of the same old
i guess instead of better i mean, basically the same in terms of ease of use
I would recommend discord.py simply because it's the most used and therefore has the most community support
You'll have a much higher chance of getting help with discord.py if you get stuck or need help
is send_embed a thing?
But ever since the incident there have been other libraries popping up which previous didn't stand a chance
yeah i know theres a bunch now. i just wanna experiment ig
but out of those, whats good?
They're all fine except pycord
whats bad about pycord?
if you're looking for something completely new try Hikari
Bad community + bad library
i heard something about hikari being kinda abstract compared to discord.py. you know much about it?
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
@bot.event
async def on_button_click(interaction):
if interaction.custom_id == "command2":
await interaction.send_message("You clicked on Command 2 button!", ephemeral = False)
elif interaction.custom_id == "command3":
await interaction.send_message("You clicked on Command 3 button!", ephemeral = False)
isnt working :(
then how...
@bot.command()
async def test(ctx):
embed = discord.Embed(title="Help Command", description="List of available commands:")
embed.add_field(name="Command 1", value="Description of command 1", inline=False)
embed.add_field(name="Command 2", value="Description of command 2", inline=False)
embed.add_field(name="Command 3", value="Description of command 3", inline=False)
class HelpView(View):
def __init__(self):
super().__init__()
async def on_timeout(self):
self.stop()
class HelpButton(Button):
def __init__(self, user):
super().__init__(style=discord.ButtonStyle.primary, label="Command 1", custom_id="command1")
self.user = user
async def callback(self, interaction: discord.Interaction):
if interaction.user == self.user:
await interaction.send_message("You clicked on Command 1 button!")
else:
await interaction.send_message("You are not allowed to click this button!")
view = HelpView()
view.add_item(HelpButton(ctx.author))
view.add_item(Button(label="Command 2", custom_id="command2"))
view.add_item(Button(label="Command 3", custom_id="command3"))
await ctx.send(embed=embed, view=view)```
It's interaction.response.send_message
yes
Oh
You can make classes inside functions and even inside other classes
It's not recommended but it's syntactically correct
Learnt something new today,๐
@slate swan what did i tell
now discord isnt logging in via static token
it stays on that
2023-07-28 02
40 INFO discord.client logging in using static token
2023-07-28 02
36 INFO discord.gateway Shard ID None session has been invalidated.


is it possible for interaction.edit_message?
im using this for my help command, with buttons, so you can select certain categories
nevermind.
can someone explain how do i correct this error?
TypeError: Interaction.edit_original_response() takes 1 positional argument but 2
were given
i didnt give 2
Can you show your code?
async def callback(self, interaction: discord.Interaction):
if interaction.user == self.user:
await interaction.edit_original_response('You clicked on Command 1 button!')
else:
await interaction.response.send_message("You are not allowed to click this button!")```
thats where im getting the error
If you meant to edit the content of a message, you need to specify that:
await interaction.edit_original_response(content="New content")
ohhhhh
can i use embeds inside of (content='')?
how do i avoid waking it up
you have to specify that too, embed=my_embed where my_embed is your embed
in a channel, idk how to call that
ok, ive made it reply to 1 button, it works, but it still says interacion failed, how do i fix this?
last thing, on this line, where do i put the buttons ID?
async def callback(self, interaction: discord.Interaction):```
custom_id?
Is this a subclass of ui.Button? you'd set it in __init__
does anyone have the documentation for python discord bot thing?
Which library are you thinking of working with?
im just looking for anything , what library would you recomend for discord bots?
discord.py, obviously
mb
discord.py is a good one if u want to build a discord bot
But inorder to create a discord bot using u will need to have an understanding of oops
How do I make my bot so that it starts multiple websocket connections in the same call so I can have like different instruments playing without overlapping its like a different voice call for each instrument with the same bot in the same voice call
Wouldn't that get you rate limited pretty quick?
You need to somehow compose all the individual instruments into one track before playing it
fix your sleep schedule
What
apparently its trying to sleep until a datetime which has already been 10 minutes in the past
what's your code? how did you specify the time for your loop? are you using discord.py 2.0 or a different library like pycord?
looking through dpy's source i cant comprehend how this is possible in the first place, so having details to reproduce the bug would be helpful
hey yall! i gotta question...how can i add buttons in my discord bot using discord.py?
i found something called discord-components, but i cant download it on vscode, was wondering if its maybe outdated?
yeah it got pulled from pypi <t:1639458000:R>, but discord.py and its forks already have native implementations
whats an alternative?
what about slash commands
what can i use for that
cani use ui too
discord.ui is for message components only, application commands are mainly under discord.app_commands
example: https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
see also this summary ive written: #1125984891784400978 message
I want to implement the following feature:
me: !ban
bot: reason
me: gives reason
bot: how many days!
me: days
bot: send dm.
me: y/n
bot: done
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
you're gonna want to use this iirc
ok, but how do I create the conversation session. after invoking !ban cmd
are you sure that's the way you want to make the command?
You could just make it require those arguments
maybe, we first listen to cmd to initiate and then start a listing session with user
it can be helful if i want to add Ai chatbot
I have no clue what you mean
lets say I want to make a chatbot.
!start will initiate the session with user. means bot will listen msg send by user in that channel. and reply to him
!stop to terminate the session.
I would reccomend you instead just add reason and time as an argument
but for this purpose. i cannot use that
this is very dangerous
anyone can ban anyone if you do that
but its for friend group. not public.
I see
any clue
@bot.command()
async def ban(ctx: commands.Context) -> None:
await ctx.send("Reason for ban?")
check = lambda msg: msg.author == ctx.author
response = await bot.wait_for("message", check=check)
await ctx.send(f"Reason set as: {response.content}")
# continue
You'd want to do something like this
I think you can understand the logic
yep, its not quite useful for QnA bot
you're gonna probably want a listener for that
yes. trying to figure that out
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
Example...
yeah so the perms are a bit messed up here:
yeah so the perms are a bit messed up here:
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(read_messages=True, send_messages=False),
r1: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_messages=True),
interaction.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}```
right now when the button to close a ticket is sent the ticket becomes public and everyone can view it, edit the code so only the person who opened the ticket can view it
i want the user who opened the ticket to be able to see the ticker; but not send a message in it
class TicketModal(ui.Modal, title="Tickets"):
inputissue = ui.TextInput(label="Explain your issue",
style=discord.TextStyle.paragraph)
async def on_submit(self, interaction):
guild = interaction.guild
moderator_role = guild.get_role(config.mod_role)
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
moderator_role: discord.PermissionOverwrite(view_channel=True)
}
category = discord.utils.get(guild.categories, id=config.TICKET_CATEGORY)
channel = await category.create_text_channel(f"ticket-{interaction.user.name}", overwrites=overwrites)
await interaction.response.send_message(f"Ticket created {channel.mention}")```
wheres the problem
Its sending the modal, but the submit button isnt working
isnt working doesn't explain the problem
How is it related?
Cogs aren't doing anything with the errors
If you have error handlers - disable them then.
If the command is running in a different file, how would i see the error in another file's terminal
what
eh
you are running multiple bots?
then why would you get error somewhere else
ok i removed the modal, still cant create the channel
because, the cog is in a different file
how would i get the error if i run main.py and access a different file for commands and still get the errors on the terminal
!paste
https://paste.pythondiscord.com/XUYA this is my code
everything is working, but the call back of the select menu isn't working
eh
i dont get errors when i load the cog
if i Restart the bot or reload the cog, i get error
but, if i run the command i dont get the errors
You didn't set the callback for it ๐คท
Set its callback before adding it to the view, or better yet, just subclass the view and get rid of that mess
You should get errors.
I runned your command and there is an error.
what
What?
It doesn't actually matters.
But would look better, yeah
You have error handlers i guess.
yes
Then you should print out the error there
If you don't do something with error inside error handler, it is just dropped
Show it
Why make an error handler and pass all exceptions 
lmao
lmao
wha
A for effort tough
what
what
That try-except will work only when you are killing the process (stopping the bot)
Do you have an actual error handlers?
Like on_error or something like this
no
Totally not because there's no logging setup
setup logging
hey? do you know how to make music bot
how
You can't just put every command inside a try except.
ะตะผะฐะต
!d discord.utils.setup_logging
!rule 4
discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.
This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig "(in Python v3.11)") but uses different defaults and a colour formatter if the stream can display colour.
This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") to set up logging if `log_handler` is not `None`.
New in version 2.0.
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
can u show me an exmple
What example? The function is as easy to use as a function can be, just call it
async def on_error()?
Before starting the bot
buthow
Call it
like, what will it go are the parameters
how would i make it to print it
log it*
Print what
If you mean logs, the function already handle all that
How what
Do what
He told you 5 times already.
Call the function before starting the bot.
What does on_error have to do with this?
eh
We're talking about logging.
how would i do it
^^^^^^
how would i call it
!d discord.utils.setup_logging
discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.
This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig "(in Python v3.11)") but uses different defaults and a colour formatter if the stream can display colour.
This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") to set up logging if `log_handler` is not `None`.
New in version 2.0.
Like any other functions
Like you would any other function.
what
got it working :> thanks
func()
can someone help me with my discord bot please? i've never seen this error before and i'm stumped
Hello, I haven't used this application in a while and I think the version may have updated.. What is a way I can import discord to my bot? I used to use import discord but i get an error.
What error
go to the shell and run the command pip install discord.py
ohh
this one @naive briar
thanks
thats related to twitch package and not discord bots
try asking in #1035199133436354600
And you'd need to send the link to that library
Because i can't find it
thank you
the thing is i didn't even import that library
You have import from twitch.api import API
That library has absolutely different imports
these are the only things ive imported
import os
from discord.ext import commands
from twitch import TwitchClient```
It is still different from what the examples are showing
And your error says that your 4 line is not like that.
well that's what my line 4 is
i have no idea how it's outputted that
You didn't save the file mb
Or running some different file
wait i refreshed it and now it says from twitch import TwitchClient
weird
this is the updated version
The library you sent uses name twitchAPI
There is no just twitch there
so how did you come up with this code
wait
accidentally imported twitch 
Seems so.
But there is no TwitchClient there.
@buoyant quail what error did u get when u ran my code
Missing required argument for selectmenu_callback
my mate said i need TwitchClient in the code for something can't remember what
do you think it might be that fact that i've installed python-twitch, twitch-python and python-twitch-client?
using pip
I don't know which library and methods you want to use ยฏ_(ใ)_/ยฏ
twitch-python doesn't have TwitchClient at all
python-twitch-client does have it
ive just looked at docs and it says from twitch import TwitchClient
that's the library that's i've downloaded
If it is the library that you've downloaded...
You have sent a lot of others
Uninstall all of them and install only needed
then it shouldn't give the error
try from twitch.client import TwitchClient mb
Actually it works fine with just from twitch import TwitchClient
It's something by you
Check that it's installed correctly
They probably have a folder named twitch
i dont
file called twitch.py?
nope
i've just uninstalled and reinstalled python-twitch-client and it fixed it, i had an intents error but i know how to fix those
thanks for the help guys
just ran the command and now i have a new error, i'll send the code and the error
import discord
import os
from webserver import keep_alive
from discord.ext import commands
from twitch import TwitchClient
client = commands.Bot(command_prefix='!',
intents = discord.Intents.all())
twitch_client = TwitchClient()
@client.command()
async def update_followers(ctx, twitch_username):
user = twitch_client.users.get_by_login(twitch_username)
follower_count = user.followers
guild = ctx.message.guild
voice_channel = guild.get_channel(1042079613339312148)
new_name = f"{twitch_username} - {follower_count} followers"
await voice_channel.edit(name=new_name)
keep_alive()
token = os.environ['TOKEN']
client.run(token)```
how can I get a list of all slash commands and their IDS
I used to be syncing the bot on_ready but then I discovered it is a really bad idea
so how can I get the same output that client.tree.sync() returns?
!d discord.app_commands.CommandTree.walk_commands
for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
An iterator that recursively walks through all application commands and child commands from the tree.
I have tried client.tree.walk_commands() but it doesn't return the slash commands ID
there's no id attribute
It returns an iterator of app_commands.Command objects
!d discord.app_commands.Command
class discord.app_commands.Command(*, name, description, callback, nsfw=False, parent=None, guild_ids=None, auto_locale_strings=True, extras=...)```
A class that implements an application command.
These are usually not created manually, instead they are created using one of the following decorators:
โข [`command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.command "discord.app_commands.command")
โข [`Group.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group.command "discord.app_commands.Group.command")
โข [`CommandTree.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command")...
I know, looping through it, the command doesn't have an id attribute
!d discord.app_commands.CommandTree.fetch_commands
await fetch_commands(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the applicationโs current commands.
If no guild is passed then global commands are fetched, otherwise the guildโs commands are fetched instead.
Note
This includes context menu commands.
!d discord.app_commands.AppCommand.id
The application commandโs ID.
That's the one
?
can anyone help me with this mini game thing im trying to make for my bot? it, kinda half works
What's the problem?
Thanks a lot!
read what it says
i did, i just need help finding a library that has that attribute
xdd
Why don't just find an equivalent one in the current library you're using
#1134496389217386638 can anyone help ? 
im trying to make my bot send emoji with a message but I am struggling. Can someone give me an example of how to add, lets say a thumbs up( ๐ ), emoji to the messages my bot would send? Please @ me when you reply. Thanks in advance
message.add_reaction("๐")
@cyan grove
i did see that and tried the unicode version of it
i might have not done it properly
i tried to do something like this
this is a pic btw
i wanted to add dog emoji but I did not implement properly
i think it will be easier and more readable when you use unicode emojis
meaning this
or if its not default emoji use the emoji string emoji = ''
so something like
message = "๐"
and then i pass the message ?
can be
programming is something new to me so what is a constants file?
A constants file is a file containing frequently used strings or a set of characters.
example of @unkempt canyon bot
It's good since if you change it in the constants it changes everywhere.
bot/constants.py lines 514 to 519
class _Emojis(EnvConfig):
EnvConfig.Config.env_prefix = "emojis_"
badge_bug_hunter = ""
badge_bug_hunter_level_2 = ""
badge_early_supporter = ""```
example snippet of emojis constants
thats a good idea
that is interesting
lets say i want to implement a dog emoji
i do something like
doggo = "<:dog: <NUMBERS> >"
i dont understand the numbers bit tho
if its a custom emoji then yes
and the numbers are the emoji id
how to get this "numbers": ```py
The name and ID of a custom emoji can be found with the client by prefixing :custom_emoji: with a backslash. For example, sending the message :python3: with the client will result in
.
the emoji must exist
\๐
\๐ถ
It's like people made it to behave that way.
doggo = "/:dog:"
something like this would return the unicode version?
no just copy the emoji from discord and paste it as string
makes sensse
๏ฟฝ
!charinfo ๏ฟฝ
\ufffd : REPLACEMENT CHARACTER - ๏ฟฝ
!charinfo ๐ถ
๐
lets gooooooooooooooooo im so pumped
thanks @slate swan @cloud dawn
you guys are awesome
lmao

i love how my bot is coming together. I can now get random xkcd comics when i use a command
Imagine Nitro smh
im a gamer so...

I want to reply so bad to this but the ToS gods will smite me.

I wanted to get random Calvin and Hobbes comic strips through my bot but I couldn't find any proper APIs
Hence you make your own.
no nitro be like
never thought of it but will do ig

ahahhaha
Lol
did you save your file before running it? you would have gotten a syntax error if there really wasnt a function under the decorator
ah nvm
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.
i have a problem with my code, does anyone know how to fix this error? TypeError: 'async_generator' object is not scriptable
i'll send the code aswell
import os
import discord
from webserver import keep_alive
from discord.ext import commands
from twitchAPI.twitch import Twitch
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
twitch_client = Twitch(os.environ.get('TWITCH_CLIENT_ID'), os.environ.get('TWITCH_CLIENT_SECRET'))
@client.command()
async def update_followers(ctx, twitch_username):
user = twitch_client.get_users(logins=[twitch_username])
if not user['data']:
await ctx.send(f"{twitch_username} does not have a Twitch channel.")
return
user_id = user['data'][0]['id']
channels = twitch_client.get_streams(user_ids=[user_id])
if not channels['data']:
await ctx.send(f"{twitch_username} channel is currently offline.")
return
follower_count = channels['data'][0]['viewer_count']
name = f"{twitch_username} - {follower_count} followers"
try:
voice_channel = await client.fetch_channel(104295318813478400)
await voice_channel.edit(name=name, reason="Updating follower count.")
await ctx.send(f"Successfully updated follower count for {twitch_username} to {follower_count}.")
except discord.errors.HTTPException as e:
await ctx.send("Failed to update follower count. Check if the bot has permissions to edit the channel name.")
keep_alive()
token = os.environ['TOKEN']
client.run(token)```
i'm getting the error with this snippet of code if not user ['data']:
also i wonder why you expect getting one user from function get_user__s__
also it returns a class, not a dictionary (and that class has no __getitem__ as i see)
because there's no attribute get_user
so i thought that would've worked
TypeError: object async_generator can't be used in 'await' expression
show your code
youll probably have to address this

I am not sure if async generators can be just awaited
You need to use an async for for them
or use the first() helper
You do use async for
twitchAPI/twitch.py lines 271 to 275
def __await__(self):
if self._authenticate_app:
t = asyncio.create_task(self.authenticate_app(self._target_app_scope if self._target_app_scope is not None else []))
yield from t
return self```
well thats interesting
would this be correct? user = async for twitch_client.get_users(logins=[twitch_username])
Of course not
oh
is there a reason why you dont want to use the first() helper function?
async for is the same loop as for
||Not reading the docs and doing random stuff||
i've just awaited it
because i don't know how to use it
looks as simple as user = await first(twitch_client.get_users(logins=[twitch_username]))
It's the first example in the docs. And it does exactly what you want to do here.
ah okay
light mode ๐ฎ
can you add hypertext in embed title? like not url kwarg but text with hypertext
i always just use the url kwarg but let me try
the problem with that is then whole title will be link annotation
i just want part of it
I believe no
and cant really test it rn
ill try after my meeting
nw
no
@client.listen()
async def on_member_update(before, after):
if after.id == client.user.id:
return
if after.nick == "Bad word name":
pass
else:
key = f'antibadwords:{before.guild.id}'
if r.exists(key):
if profanity.contains_profanity(after.nick) or profanity.contains_profanity(replaceDoubleCharacters(after.nick)):
new_nickname = "Bad word name"
await after.edit(nick=new_nickname)
log = r.get(f"logs:{str(after.guild.id)}")
embed = discord.Embed(title="nickname changed", description=f"{after.mention}'s nickname was changed")
embed.add_field(name="Reason", value="contained bad words")
embed.set_footer(text="Censored by better_profanity")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
print(f"1bad word detected logs: {after.guild.id}")
``` if someone joins it changes their name to bad word name even though its not a bad word
and what contains_profanity and replaceDoubleCharacters are?
would anyone like to help work on a brand new Discord API wrapper?
those are generally considered difficult
Nice! I've built a few but never finished. They are a lot of fun. If you need help you can ask in #965291516031549500
getting errors for these how do i fix it
And what's the error?
probably not installed?
errors are fixed
my commands dont work now tho
i can send the code
Is this your code
"doesn't work" isn't too descriptive, are you getting any errors? is your bot responding to the command at all?
no errors
bot is not responding
i fixed it
it was the bot token
yo so im having a problem when i go to type my command nothing happens but it doesnt look like there is any problems with my bot when i put it up
this is all i see i dont know if it means anything
try resetting your token
alr thanks
did it work?
nope
damn
Show your code
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
what r u usin the bot for, im only in this code for discord bots personally mines for a shop
verifying in my discord
It's discord.py
discord is a wrapper for discord.py
!pip discord
A mirror package for discord.py. Please install that instead.
both works fine
no it's just a mirror
presumably to prevent typosquatting
i fixed it already
good
iโve installed it n i keep getting the same error
do pip install discord.py[voice]
requirement already satisfied
i already had it installed
do you have multiple python versions installed in your pc?
if you're on windows you can do
py -3.10 -m pip install -U discord.py[voice]
you can replace the 3.10 with the python version that you're using
what
You know discord.py Has slash commands built in already
You dont need external module
in the source code
it provides an instance already
I am unable to find it? can u link it to me??
where the instance is get created??
What
why would you need to know
discord/state.py lines 1619 to 1620
def create_message(self, *, channel: MessageableChannel, data: MessagePayload) -> Message:
return Message(state=self, channel=channel, data=data)```
if you are trying to create message object yourself there are methods for this
!d discord.abc.Messageable.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
And not only here
But i don't see a reason to send them all until we don't know what are you doing
Yo @rancid grail
can you guys update discord library?
so we can send ephemeral messages by using that library?
Wdym by "so we can send ephemeral messages"? If you mean "we" as users doesn't make much sense since that's in discord's hands whether or not they update the client to make that possible. If you mean for @unkempt canyon, @novel apex or @lament depot; I suppose you can ask in #community-meta or one of the dev channels
i meant my discord bot by "we"
idk if that's what you mean, but you can send ephemerals in discord.py
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
ephemeral arg
Do you think this is a good structure for a command based bot ?
everythink is made with classes except main.py which contains 4 lines
basically it's a .run with the token loader
btw I'm using pycord
wait we can???
I want to modify it a bit
i think i saw you somewhere
whrer??
k
What exactly you want to do maybe there is a solution already
How want to know, @bor.event works, like for interaction , message etc where the instance of objects gets created
https://github.com/Rapptz/discord.py/blob/master/discord/state.py#L619-L620
dispatch goes into events and listeners later
discord/state.py lines 619 to 620
message = Message(channel=channel, data=data, state=self) # type: ignore
self.dispatch('message', message)```
is it like this
await ctx.send("This is an ephemeral message!", ephemeral=True)```
alr i will take a look at it
Ephemerals exist only in interaction responses
can i use it on embed message reaction?
for example assume my bot send a embed message with 2 reaction
if 1st reaction is press then a random Ephemeral message will be send to that user
if 2nd is press then ||NOTHING WILL HAPPEN LOL||

this embed file structure reminds of css modules ๐ฟ
is it bad ?
why seperate files for embeds
idk
is one file not enough for all the embeds
Super speed optimization 
why not
ok means i can't modify my bot
it becomes a mess cuz there will be about 40 embed classes
so
40 x 30 lines
it's a lot
why do u need 40 embed classes why u need sn embed class if first place
30 lines for one embed???
Ultimate speed optimzation 
what does it fo for the embed
idk actually it's about 10
GENIUS
so why not just a single embed class with static methods which returns embed instances
wdym
the best solution for embeds is to store them as dicts
json
Storing embeds as dictionaries is a common practice
And all the requests, stuff is in the embed class
ah
also felixable
weird but ok then ig
Well then it's not just an embed if it handle some other logic
And should cogs be only in one class ?
i like having logic and ui seperated
me too
that wasn't my point but ok
guys if i wrote a 400 lines of discord bot , am i pro discord maker then?
mh? you can have more than a cog in a file
ik
long way off buddy
when I didn't know what cogs and extensions were I wrote a bot of 800 lines
with blocking code as well
it was my dark era
sight what to do standards have risen now we can no longer impress ppl with hello world
everyone's been through it

390 empty newlines 
๐
i actually wrote 400 lines no joke
i believe
399*
it's not a lot
*pain in my heart just striked me
am i the unique one that you guys left to die but i didn't die?? 
bye ( everyone dead rn )
We all had one of those I think
hello, i'm getting the error below but i'm using the helix api not the kraken api, how do i fix it? here's the code and error:
client = TwitchClient(
client_id = os.environ['TWITCH_CLIENT_ID'],
oauth_token = os.environ['TWITCH_OAUTH_TOKEN'])
users = client.users.translate_usernames_to_ids(['graveyardztv', 'coinzplayz'])
for user in users:
print('{}: {}'.format(user.name, user.id))
I don't think this is Discord bot related, I'd recommend posting your question in #1035199133436354600 instead
it is, i'm building the base of a discord bot. i want it to return the follower amount of a twitch user then use that integer to edit a voice channel name, eg: Twitch Followers: 72,272
i'll get there eventually i just want to make sure that it actually returns the follow amount before i start that
i'll post it in python-help in hopes for help
That error isn't related to Discord bots
okay, sorry
Use it ๐คท
Use it, I said it
If you defined something and leave it unused, it's kinda pointless
i was using this script before it was perfect wat appen
i need to use it on the script ?
lemme see
requests package != resquest package
you imported that module but u never used that module in your code
Halp someone
then i delete it ?
or i need to use it in my code
i mean, you can remove that line if you dont want it, its kinda pointless to import a module that u dont want to use
ok thank !
If you don't need it, just delete it ๐คท
thank
@naive briar halp me pls
the error says what to do ._.
privilaged intents ._.
Read the error then you will know
pandaaaaaaaa
@cloud dawnhalp
yes
:3
:D
wao
Can you print & verify the validity of the category object?
Hmm nevermind it's crying about the permissions.
lots of pandas here
Shouldn't that be import request?
You misspelled it
wdym
wasn't the package name requests
You shouldn't be using request for discord bots anyway
!pypi requests
aiohttp ^^
its requests
ye
It's blocking
wha
requests a non async
just say its sync ๐ฟ

Can someone help here?
#1134838949722980352
@sharp whale Does moderator_role have an .id attribute? It's trying to get all .id's from all permission targets.
basically it won't "run in the background" when u use it but instead it'll block the entire process of the bot until it finishes
fair
the moderator role is itself a snowflake
wao
async def selectmenu_callback(interaction):
print([x.id for x, y in overwrites.items()])
creator = interaction.user
category = discord.utils.get(guild.categories, id=config.TICKET_CATEGORY)
channel = await category.create_text_channel(f"ticket-{creator.display_name}", overwrites=overwrites)
await interaction.response.send_message(f"Ticket created {channel.mention}", ephemeral=True)
@sharp whale I assumed you fixed it?
what
nope
overwrites ={
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
moderator_role: discord.PermissionOverwrite(view_channel=True)
}```
this is my overwrites
I know.
I added a debug print
wait
@cloud dawnpy Traceback (most recent call last): File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task await item.callback(interaction) File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 80, in selectmenu_callback print([x.id for x, y in overwrites.items()]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 80, in <listcomp> print([x.id for x, y in overwrites.items()]) ^^^^ AttributeError: 'NoneType' object has no attribute 'id'
hmm we need to isolate the one that does not have a .id
Mr. Turtle typing
how about you do ```py
for item in overwrites.items():
if not getattr(item, "id", None):
print(item)
!e
getattr(None, "id")
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | getattr(None, "id")
004 | AttributeError: 'NoneType' object has no attribute 'id'
Before the overwrites add this ```py
print(guild.default_role.id, interaction.user.id, moderator_role.id)
nope it raises
Set a default value
yeah updated code
Or use hasattr instead
@sharp whale I recommend doing this.
actually forgot it exists
Haven't thought about it either 
!e print(hasattr(None, "id"))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
It's a Nonetype object so it doesn't have hasattr.
but hasattr isnt a method
@cloud dawnpy Traceback (most recent call last): File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task await item.callback(interaction) File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 80, in selectmenu_callback print([x.id for x, y in overwrites.items()]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 80, in <listcomp> print([x.id for x, y in overwrites.items()]) ^^^^ AttributeError: 'NoneType' object has no attribute 'id' [2023-07-29 19:26:20] [ERROR ] discord.ui.view: Ignoring exception in view <View timeout=None children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Open Ticket' emoji=<PartialEmoji animated=False name='๐ฉ' id=None> row=None> Traceback (most recent call last): File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task await item.callback(interaction) File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 35, in ticket_callback print(guild.default_role.id, interaction.user.id, moderator_role.id) ^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'id'
Called it
moderator_role ๐ง
!e
print(hasattr(None, "id"))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
Something is wrong with the moderation_role
looks like it returns None
What is config.mod_role?
if get_role returns None you might thing of using the fetch_role
Just create a snowflake then.
or fetch_roles since fetch_role doesnt exist
discord.Object(config.mod_role)
Well create channel only needs the id so no need to make an unnecessary API call.
ah so he doesnt need the Role object
Just the .id attr
then why use get_role using id just to access id attr
Dunno
Also @sharp whale if a traceback is unclear use the discord.py github to know what the code does and what it's pointing to. https://github.com/Rapptz/discord.py/blob/master/discord/guild.py#L1215-L1246
wha
Well you didn't understand the traceback most likely, wich I understand but if you look up the line inside the source you can see what it does and where the issue might be.
oh
Meaning you only needed to create a snowflake, uses less resources.
No since the overwrites only need the id nothing else.
overwrites ={
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
config.mod_role: discord.PermissionOverwrite(view_channel=True)
}```
That's not what I meant.
uhh
You just told me mod_role is just the id?
yes
Is mod_role an int or a snowflake?
thats why i used get_role()
int
Okay look lemme visualize
int and snowflake same things right?
def _create_channel(
self,
name: str,
channel_type: ChannelType,
overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = MISSING,
category: Optional[Snowflake] = None,
**options: Any,
) -> Coroutine[Any, Any, GuildChannelPayload]:
if overwrites is MISSING:
overwrites = {}
elif not isinstance(overwrites, Mapping):
raise TypeError('overwrites parameter expects a dict.')
perms = []
for target, perm in overwrites.items():
if not isinstance(perm, PermissionOverwrite):
raise TypeError(f'Expected PermissionOverwrite received {perm.__class__.__name__}')
allow, deny = perm.pair()
payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
if isinstance(target, Role):
payload['type'] = abc._Overwrites.ROLE
else:
payload['type'] = abc._Overwrites.MEMBER
perms.append(payload)
parent_id = category.id if category else None
return self._state.http.create_channel(
self.id, channel_type.value, name=name, parent_id=parent_id, permission_overwrites=perms, **options
)
``` this is the create role function
Look at this line for target, perm in overwrites.items():
target will be all the key values of the overwrites dictionary.
what
Then it will go to payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
Where target is all the different key values inside the overwrites. And it will try to get the attr id.
uhhh
So it will do this everytime ```
guild.default_role.id
interaction.user.id
config.mod_role.id
Is this possible?
no

