#discord-bots
1 messages ยท Page 121 of 1
make multiple embeds in a single message :)
thats a thing?
Mhm you can add an embed with an image, then another with a text. otherwise the text will be above the text ^^
and they'll be in one single message
Not sure if im understanding, how would you add an embed to the same embed in the first place. It sounds really interesting though
just put the text in the footer
embeds.append(discord.Embed(color = your_color, description=your_description))
Yeah that works but i'd rather have the text a little bit bigger than the footer. Id also like the text to be bold and italic at some places
embeds = discord.Embed()
embeds.append(discord.Embed(color = your_color, description=your_description))
await inter.send(embed=embeds)
Like this?
hmm, then here if embeds is a list then how would I send it out. Does the embed= parameter accept a list of embeds?
embeds = embeds
embeds = list()
embeds.append(discord.Embed(color = your_color, description=your_description))
embeds.append(discord.Embed(color = your_color2, description=your_description2))
await message.channel.send(embeds=embeds)
youre a legend im going to try that out
it's embeds=embeds
embed only takes a single embed
right sorry
import discord
from discord.ext import commands
import random
TOKEN = 'TOKEN'
prefix = commands.Bot(command_prefix='/')
client = discord.Client()
@client.event
async def on_ready():
print('hello')
@client.event
async def on_message(ctx):
await ctx.send('Hello')
prefix.run(TOKEN)
I hope it works first
xd yeah
i want it to reply message to me but am i doing something wrong?
you welcome :)
@bot.command(name='hello')
async def on_message(ctx):
await ctx.send('Hello')
You forgot to add the decorator for the command name :)
now when you run /hello it should show
ok thanks
you can't make a command out of a pre-existing event
you need the message_content intent in your bot object and enabled in dev portal
And it must listen to events, right now you aren't listening to anything and your code will raise an attribute error
right just remove @client.event on that and that's it
@client.event
async def on_ready():
print('hello')
@bot.command(name='hello')
async def on_message(ctx):
await ctx.send('Hello'
this works
technically you can, nothing's stoppin you
anyone know of a way to get the user who invited your bot to the guild that doesn't require 'dangerous' server permissions e.g audit log access?
alr thx
i mean sure if you only want one to work
no it won't he doesnt have message_content intent
i really dislike dpy's event handling for the same reason
name based events
what is the bot variable from?
is it the prefix?
u named ur bot object prefix lol.
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
oh ok lol
that's called a decorator in python, it sorta lets you edit a part of a class method ^^
also add intents to your bot like so:
bot = commands.Bot(command_prefix = '/',
intents = discord.Intents.all())
and it should stop that error message tho
thx
yo so if i dont want my bot to send in a channel, it would be like py if message.channel.name != 343944376055103488: right?
and if its multiple then it would be py blocked_channels = '343944376055103488, 813178633006350366' if message.channel.name != in blocked_channels:
right?
use channel ids, channel names can change, ids no
sooo
if message.channel.id != id: ...
and is there a more efficient way to do it
if message.channel.id not in (id1, id2, id3, ...):
# do something
so not in > != in
but not in = != in
what
they are not the same thing, also != in is invalid syntax
Because in isn't a valid operand
!= means not equal to
in means sequence with a specified value is inside the object
in wording is not mine
Not always
You can of course override the dunder and do some weird stuff
!e
class Foo:
def __contains__(self, item: "Any") -> None:
print(item)
1 in Foo()
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
*normally
๐

msg = await bot.wait_for('message', check=check)
I'd like to pass ctx inside the check
how can i do it?
Why?
declare the check inside your command function so you have the ctx in your scope
that's what I wanna say, I'd like to know if there's a trick to take it out
or use a lambda if its not too long
The method returns the message object, if listening to a message, so if you're going to compare authors you can always compare them from the caller
yeah there is ```py
def check(ctx, msg):
async def command_function(ctx):
msg = await bot.wait_for('message', check=lambda msg: check(ctx, msg))
Thats an interesting way non the less
lambda? :ooo
YESS SARTH THX ! A new thing to learn <33
lambdas are single lined functions
quite fun to use
Something else I was looking for a while back but never found so I worked around it 
can somebody help real quick. should be easy. i just can't figure it out. where would i put this...
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', session=session)
await webhook.send('Hello World', username='Foo')
in this...
https://github.com/grasshaussoftware/support-bot-piphi/blob/main/bot_2.py
support bot for https://piphi.network discord server - support-bot-piphi/bot_2.py at main ยท grasshaussoftware/support-bot-piphi
im trying to send a notification to a webhook when a new ticket is created
Is there any part of your code that you haven't needed help with? Seems like you've been in here for days
i know. i have been
there have been worse
but that's why we're here, eh?
Yea I mean at least it's something that's not super basic
I'm always glad to help anyone, so long as it's not something that can easily be solved with a little research C:
But what is the problem here?
Any errors? What happens when you call the function?
Try a print statement inside of the function to see if it's being called
I've been popping in trying to help out with the easy stuff when I can
And learning from other people's errors
can i do this....
await interaction.send(f"I've opened a ticket for {user.mention} at {channel.mention}!", ephemeral = True), foo()
put it at the end of the line?
No need for that
Just a simple print statement inside of foo() to see if it's being called
async def foo():
print("Sending webhook notification...")
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', session=session)
await webhook.send('Hello World', username='Foo')
but if its not being called anywhere...
Of course it wouldn't send the webhook notification then
okay so i gotta call it somehwere
preferably along with the ticket creation
i finally got some sleep last night
i was up for like two days i think
Just working on this?
yeah
Nah I put sleep above everything
im trying to impress some new friends
Baby keeps me up too late, I call into work so I can sleep lol
aye
progress...
/home/deusopus/Desktop/ticketing_bot.py:35: RuntimeWarning: coroutine 'foo' was never awaited
await interaction.response.send_message(f"I've opened a ticket for you at {channel.mention}!", ephemeral = True), foo()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
why u calling foo after sending? why not call before
also you need to await it, it's async
Anyone know what the regex is for Discord's valid link format? Aka when they do embed it.
Regular Expression to Capture any discord link
This isn't what I meant.
Like google.com is a valid url but https://google.com, gets blue and gets an embed.
Looks like it.
so it calls main() here. should i put it in main()?
nm
that doesn't work
its not getting called robin
what you're trying to do
so...
thanks btw
await channel.send(f"{interaction.user.mention} created a ticket for {user.mention}!", view = main())```
this needs to be sent to a webhook
i have the webhook function
called foo
and you're getting this error?
yes
i was doing this....
await interaction.send(f"I've opened a ticket for {user.mention} at {channel.mention}!", ephemeral = True), foo()
foo is a coroutine, you need to await it
await foo()
what
one sec
now im getting this
ERROR discord.ui.view Ignoring exception in view <ticket_launcher timeout=None children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Create a Ticket' emoji=None row=None>
Traceback (most recent call last):
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "/home/deusopus/Desktop/ticketing_bot.py", line 35, in ticket
await foo()
File "/home/deusopus/Desktop/ticketing_bot.py", line 108, in foo
await webhook.send('Hello World', username='Foo')
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 1726, in send
data = await adapter.execute_webhook(
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 176, in request
async with session.request(
File "/home/deusopus/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1141, in __aenter__
self._resp = await self._coro
File "/home/deusopus/.local/lib/python3.10/site-packages/aiohttp/client.py", line 400, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed
i guess it wants me to do foo(self)
now i get this....
Traceback (most recent call last):
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "/home/deusopus/Desktop/ticketing_bot.py", line 35, in ticket
await foo(self)
File "/home/deusopus/Desktop/ticketing_bot.py", line 108, in foo
await self.webhook.send('Hello World', username='Foo')
AttributeError: 'ticket_launcher' object has no attribute 'webhook'
Hyperlinks?
Well, I can't guess the problem, show your code
now ive got this...
Traceback (most recent call last):
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 138, in __call__
return self.callback(self.view, interaction, self.item)
TypeError: ticket_launcher.foo() takes 1 positional argument but 3 were given
ill show you
class ticket_launcher(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout = None)
self.cooldown = commands.CooldownMapping.from_cooldown(1, 10, commands.BucketType.member)
@discord.ui.button(label = "Create a Ticket", style = discord.ButtonStyle.blurple, custom_id = "ticket_button")
async def foo(self):
print("Sending webhook notification...")
async with aiohttp.ClientSession() as session:
self.webhook = Webhook.from_url('https://discord.com/api/webhooks/..../....', session=session)
await self.webhook.send('Hello World', username='Foo')
```
what args are you passing to call foo?
btw to fix this error just don't use a context manager and close the session whenever you want to
self
umm
in discord.py should functions have specific names?
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on2_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
@client.event
async def on_message(message):
if message.content.startswith('$greet'):
await message.channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == message.channel
msg = await client.wait_for('message', check=check)
await message.channel.send(f'Hello {msg.author}!')
client.run('$$$$')
the function with on_message title is the one that works only
when I swap names the other works
have you looked at the docs?
well it didn't mention anything related to that ๐
yes
maybe it did but I am dumb
oh
ERROR discord.ui.view Ignoring exception in view <ticket_launcher timeout=None children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Create a Ticket' emoji=None row=None>
Traceback (most recent call last):
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "/home/deusopus/Desktop/ticketing_bot.py", line 58, in ticket
await foo()
File "/home/deusopus/Desktop/ticketing_bot.py", line 70, in foo
await webhook.send('Hello World', username='Foo')
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 1726, in send
data = await adapter.execute_webhook(
File "/home/deusopus/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 176, in request
async with session.request(
File "/home/deusopus/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1141, in __aenter__
self._resp = await self._coro
File "/home/deusopus/.local/lib/python3.10/site-packages/aiohttp/client.py", line 400, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed
but how can I give 2 functons the same name then
!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...
u can't?? why would u even do that
ohh
i mean you can but they both won't work
two different function can listen the same event
so I need to put all the functionality in 1 function?
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
@client.event
async def on_message(message):
if message.content.startswith('$greet'):
await message.channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == message.channel
msg = await client.wait_for('message', check=check)
await message.channel.send(f'Hello {msg.author}!')
client.run('$$$$')
``` instead of this
this ```py
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
if message.content.startswith('$greet'):
await message.channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == message.channel
msg = await client.wait_for('message', check=check)
await message.channel.send(f'Hello {msg.author}!')
client.run('$$$$')```
or what?
btw seems like you're trying to make commands, are you following an outdated tutorial?
@glad cradle here is the github of my code right now
im trying to figure out where to call foo()
Learning discord.py. GitHub Gist: instantly share code, notes, and snippets.
support bot for https://piphi.network discord server - support-bot-piphi/bot_3.py at main ยท grasshaussoftware/support-bot-piphi
don't follow links from strangers
when I asked for a tutorial
haha
XD
yes but if you want to create command you should use commands.Bot
Umm
it already handles things for you
do you have an up to date tutorial that I can read?
without bothering you with useless stuff
the docs have a decent bit of examples
okie
ty mate
this example is a little bit outdated
intents is required now
i mean its a direct link from their "stable" documentation so typical dpy
I am a bit confused
sorry, I'm going to sleep, also I can't understand a thing coz I'm tired and the code is pretty dirty
it's also not even listed in their change logs or anywhere on their documentation lol
You're making me doubt what I said
should I read what they gave me or is it outdated?
use disnake
lmao. updated guides, cool community, and lots of UPDATED examples and guides
idk I couldn't find it anywhere lol
oh so instead of putting into change logs its in a seperate table of contents listed under "Migrating to 2.0" lol
you can read it, just add the intents kwarg when creating the Bot object
okie
thanks
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
if message.content.startswith('$greet'):
await message.channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == message.channel
msg = await client.wait_for('message', check=check)
await message.channel.send(f'Hello {msg.author}!')
from discord.ext import commands
bot = commands.Bot(command_prefix='$',intents=intents)
@bot.command()
async def test(ctx):
await ctx.channel.send(f'Hello ! banana')
client.run('$$$')```
@slate swan
the last bit doesn't work
the bot command bit
the rest works tho why?
why u using client and bot?
just use bot
bot = commands.Bot
@bot.event
oh
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$',intents=intents)
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
if message.content.startswith('$greet'):
await message.channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == message.channel
msg = await bot.wait_for('message', check=check)
await message.channel.send(f'Hello {msg.author}!')
@bot.command()
async def test(ctx):
await ctx.channel.send(f'Hello ! banana')
bot.run('$$$$')```
the last bit still doesn't work
it's cause ur using on_message as well hold on
will read that
so I can't use that?
you can
oh k I found the solution in the article
ty
yup np
I want to get someone's ID when they call a command
?rtfm Message.author.id
oh woops
!d discord.Message
!d discord.Message.author
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id "discord.User.id")
there u go
just use bot commands
and not on_message
trying to salvage someone elses code for a welcome image bot when new members join. however, it was last updated over a year ago and its stuck trying to grab the joining members profile pic. the code uses pillow and the error im getting is that the pfp url is a string and thats not callable
also tried the pfp itself without the .url and that doesnt work
oh yea dc changex that up
*changed
*dpy
any docs on what i need to do?
u want to get their avatar rigjt?
yea so i can put it on a background image
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
it returns discord.Asset
which has a .to_file and a .read
and also ,url but u won't need that
alright ill see if i can get that going. thanks
np
How do I install discord.py. Iโve tried pip install discord.py and python 3 -m install -U discord.Py in IDLE, and terminal but I keep getting syntax errors. Iโm using MAC OS
Type exit() first, then run the command to install discord.py
It did end up running the command but ended with this error message
Failed to build frozenlist multidict yarl
ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects```
if ur using easy pil. you can do this
profile_image = await load_image_async(str(member.avatar.url))
that will give you the users avatar image then u can do whatever with it
ive got it working just need to resize my background image and find correct coords for the pfp. thanks though
Can you please tell me what is the best regex for filtering youtube links?
i keep getting this error when i try to install discord
Download microsoft c++ build tools as the error says
me too
is there one for mac?
it says n thumbnail vs for mac
Probably
I see, on the website I don't see an option to download for mac
click download tab
at im still getting error
@frozen rain @nocturne totem if either of you want to skip the build tools stuff, you can downgrade to python 3.10 which has prebuilt wheels for the dependencies listed in your error message
after closer reading. I do not have the same error message as them.
The build tools are like 6gb+
this?
Desktop development with c++
should I uninstall and reinstall, or is there a command to do it?
i wouldnt know the specific instructions as i havent used python on mac
How can I make like a xp bar on a embed? that will fill depending on a variable? is there any exmaple that I could see?
Looks like your on mac, so you should install the xcode toolkit
I think the command was xcode-select something maybe --install?
Or you can download it via the appstore
would it be better to do that or downgrade to python 3.10?
Well, you should've installed xcode a while back for Mac if you code (or at least that's my opinion)
I use it for some other stuff like my wm
I would just install xcode instead of downgrading
Hi again guys !
How do you use unittest during your bot developpement?
There are probably external libraries you can use to mock gateway events, but I would assume for unit testing you'd be mainly dispatching manually a mocked gateway event, such as await Bot.dispatch("message", <discord.Message>)
It's quite cumbersome and I don't really see the merit from unit testing your bot considering that you could just add checks into your code
!src
if you look at our repo we use testing for our bots
We've got discord.py mock objects
it's because I want to learn unit testing and best way is by practice so merged that objective to my bot recoding objective 
I'm trying to recode by bot by renaming my functions smarter, following pep8, having a smarter and more readable code, and incorporate OOP, unit testing, and use sqlalchemy
anyone knows?
I'll check this now. When you say our bots, who is our mentionning?
The Python Discord Organization
Alright !
I mean, you can do it but it's gonna be cumbersome, if you take a look at @unkempt canyon's unit testing you can see a bunch of mock objects too
Thank you Robin !
Unit testing in my eyes would make sense for utility methods or other helper methods
I don't know what cumbersome means
It's gonna be annoying
We try our best to follow all of these. If you ever need inspiration/help on how to do something a certain way, it's a resource ๐
Also we developers can be extremely lazy now a days, I don't even remember most of pep-8 unless it's naming conventions, 90% I just use black to format my code
Yeah actually I got hired as a python dev i'll start working in junuary or febuary, and till there i need to sharpen my skills a lot
once I download it from the appstore can I still make my discord bot in VS code?
that's why I want pep8 to become such a habit that I can't be lazy to follow it, it'd just be my way of coding
Well yea it would be good to remember the naming conventions but that's really all there is to pep-8 as of now
Your IDE already formats tabs -> 4 spaces
Your IDE already does indentation for you
Etc
are their any resources available to aid learning discord.py? If so what are they?
Yes, and also good programming logic, and easy smart coding. Like I'm currently spending my time staring at this bit of my code, trying to make it shorter, smarter, simpler, my goal is that anyone could understand what it does by a single glance
def filter_user(ctx, message):
# Function that checks if a message contains an ID, a mention
# or the word 'cancel', and ignores reply mentions
return (message.author == ctx.author
and message.channel.id == ctx.message.channel.id
and not message.reference
and (message.content - message.mentions == None
or message.content.isdigit()
or message.content.lower() == cancel))
async def await_message(ctx, bot):
# Funcion that will wait for a filtered reply, return False if it is a
# cancel, user ID otherwise.
user = None
while user is None:
message = await bot.wait_for('message',
check=lambda message: filter_user(ctx, message)).content.lower()
if message.content.lower() == cancel:
return False
And I'm scared the day I start my work, collegues will mock me because I code bad 
Does message.content - message.mentions even work?
I... didn't try it yet ngl
Isn't that str - list[discord.User | discord.Member]
Which would error in my eyes as of now
Since these are of two different builtin types
Also your using cancel here as a name/variable, not a string literal which will have an undefined error
Should be content.lower() == "cancel"
no it's a questionnaire, bot asks and awaits for a response that matches conditions, and if you write cancel it stops the questionnaire
Oh you defined it else where
yes unless cancel is a function it should be "cancel"
ah yeah it should indeed lol
but it's a variable in the top
that isn't really smart indeed, it would be clearer with just "cancel"
Also your check has an oversight when it comes to "id"s
You only check for isdigit not some 64 bit integer
So I could just pass 1 and it'll probably pass
what if I then use soemthing like this:
async def check_id(bot, arg):
try:
await bot.fetch_user(arg)
return True
except discord.NotFound:
return False
and check for await check_id(bot, message.content) ?
i ain't gonna lie
You could, but if you need the user | member object of the ID passed later I would recommend a converter as you already have ctx
u are better off using slash commands and modals lmao
One simple trick to make your codebase already much better - typehint everything!

how can I stop this function ?
Also if you ever typehint make sure you actually have a type checker installed
Otherwise you'l hate your past self
ah yes ! alright I will !
oh mmmh... do you have a source about what type checkers are and how i can install on vs code? :D
or stop as stop allows the function to finish
Vscode if you install the "python" extension it comes bundled with pyright
So you should already have a type checker
Can I put it in the function ?
You could probably test via py foo = "bar" reveal_type(foo) should say foo is of type str in your IDE
oh alright !
i have no actual idea never used stop or cancel
okay thank you anyway!
Also I recommend for your check spacing out the expressions instead of having one huge expression block it makes it harder to read for some people
what about message.content.split(' ') - message.mentions ?
blank space between each or or and statement? is that pep8 friendly?
It's still list[str] - list[discord.User | discord.Member]
It's a filter
That filters what?
message.mentions -> list so if empty means there is no mentions
Well I want the bot to wait for a message that container either NOTHING more than mentions, or a valid id
if you just wanna check if there is no mentions do like if not message.mentions
and that's the function that will just return if this condition has been satisfied or not
so i can pass it to await bot.wait_for()
@cerulean folio as a related pointer, i think you can ask more about general style/refactoring in the channel #software-architecture
I know, but it's not the point. The point is that if there's a mention + other stuff, I don't want this message to be captured
Also is there a reason your only doing this via wait_for? You cannot refactor this into a message command or something?
use and with your statement
yea i already suggested using commands with a modal
if not message.mentions and message.content.isdigit()
So, if there is no mentions and the message is only containing digits
For example
hello @dude how are you wouldn't be captured
@dude would be captures
I have 27 years old wouldn't be captured
13554 wouldn't be capture unless it's a valid discord id :D
Yea, just add a couple of ands
You're probably right, but since I'm doing both styling and bots I get confused on where to ask?
It looks like you want a MemberConverter
discord-specific stuff would be fine here since you'll get people that know about the API/library you're using
MemberConverter might be overkill if you use mentions, but I'd def use it for IDs as there could be multiple ways to search
Ok so here's the thing, the bot needs to ask Who is the member? and will wait for a correct answer which is either a valid ID or a mention. But I want the user to be able to speak freely without the bot stopping on anything they say if that makes sense so when the bot asks for the member, you could chat until you either write @dude or 135438451335654 for eg
I'm sorry for poor explainations
Well you were on the right track but one of your expressions wouldn't have worked
That being checking if the content only has a mention
message.content.split(' ') - message.mentions
I thought this would return True if there's something remaining from deleting message.mentions from message.content.split(' ') and False if not? So I just need to actually invert it, so I need not (message.content.split(' ') - message.mentions). Am I wrong?
message.content == f"<@{message.mentions[0].id}>"
Assuming message.content is of "@user" then message.mentions[0] => <discord.Member> | <discord.User> where this is representing user so then, .id to format the checking string into <@user_id>. If that matches with the message content that means the message only has that single mention and nothing else.
Also it might not exactly be <@user_id> I forgot whether or not discord sends GW messages as the raw or changed version
So you should test with a message and print out the content first
right this is confusing I'll test it and keep you in touch. i'll just for now not all those precious advises from you and Robin
Also thanks a lot for all this support u guys are awesome ! <3
You should also first check if message.mentions even has a mention e.g len is not 0 or use if to check if truthy
Anytime, my friend
Yup !
TLDR: I'm looking for an opportunity to assist someone in developing their discord bot project/idea and wanting to get my feet wet again.
Hey everyone, just had a job interview go horribly bad with multiple technical interviews about doing some work in python with other things. Even though I have past experience with Python in a previous job doing some scripting and testing, I haven't practiced the language in a while (not really sure what I was thinking when I applied), and those interviews humbled me real quick. Overall I have past experience as a dev but it was more along the lines of infrastructure and not as much on the application side.
Would there be anyone kind enough to let me pitch in as a contributor for their discord project? Am willing to add to wherever areas I can and want to be a long term contributor alongside someone or a team with their project.
Also, don't know if this is the right place to ask this, but figured I'd start somewhere.
btw @pliant gulch I can code a tiny regex checker for not (message.content.split(' ') - message.mentions) wouldn't it be a good idea? like I try to isoate anything that isn't <@bunch of numbers> and see if the result is of length 0?
Hello! We're glad to have you with us. I can see where you're coming from, and why you want to improve your skills. I think the best bet for you currently, while also taking into account your interests, is to contribute to open source software. That doesn't have to be Discord bots, of course, but it seems to be what you're interested in. If you run !src, you can get a link to @unkempt canyon's codebase on GitHub where we accept code changes to add new features, patch existing bugs, etc. @lament depot is more oriented towards people just getting their feet wet (such as yourself). The codebase is significantly easier to work with as well. You will find the repository under the Python Discord GitHub organization. The "to-do" items can be found under "issues", where after discussion, you can ask to take up a certain issue. It will be assigned to you and you can then work on it. If you've got any questions, feel free to pop over to #dev-contrib and ask us there. The channel is meant for contributors or potential contributors such as yourself.
On another note, if you want to improve your Python skill all around to become more well-rounded in regards to Python as a whole, !resources has a bunch of resources on all the different fields under the sun that you can learn about. Then, you can use the !projects command to get a list of projects that you can attempt to do yourself. As a community, we're here as a support structure, so if you ever need help with any of that, you can feel free to ask about that and we'd be willing to help!
Regex is way slower than what I showed you. Remember what you said earlier? Try to be more simple and not more complex, regex means importing 're' then using a regex pattern which is slow. Why not just check if the message content equals a string you created?
And doing it that way instead of regex also means you wonโt need to check how many matches, youโd only need that
thing is, python is already as slow as molasses as a programming language, so what's wrong with the code being a little slower?
Thank you I appreciate the response. I'll see where I can get started
Alright i'll try it :D
I donโt understand why people say, oh yea python is slow so whatโs the harm?
if you want the code to be fast you should just... use C++ or something-
Yup. In the future, #pedagogy might be a better place if you wish to ask more questions about your learning. Good luck!
"haha python slow" bandwagon
Thatโs not what Iโm mostly going towards
Regardless of language you wanna be efficient
Not a lot of merit behind it, when you consider other factors than solely cherry picking runtime speed
true ยฏ_(ใ)_/ยฏ
Even C++ can be slow if you write like O(n^6) algo or something
that would be painful to watch
But generally speaking, as Luna said, I wouldn't worry about speed too much in Python
Not the primary goal of the language, it's not built with speed in mind either
Use whichever option you're more comfortable with, or whichever is more readable
Comparing C++ to python is kind of like comparing apples to oranges imo
3.11 is a bit faster than the previous versions of python, but either way it's still going to be pretty slow, try not to focus on speed unless it's causing a huge detrement to the program
The two languages completely cater towards different things
I also think Cpython is removing the GIL for some other alternative which will hopefully boost the speed
But in the current context do you really want to, Regex search, Len check then do whatever, or just check == of the string then do something?
The global interpreter lock
Itโs why python is so slow
That and itโs interpreted
compiled will almost always be faster than interpreted, i think
Probably but also I think it depends on the source
Also the optimisations
Like if you didnโt optimise your LLVM ir or something
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
im confused. why not just call the function inside the command?
lol so ur using someone else's code and dk what ur doing. u should probably mention that. google how to call python functions
calling a function is basic python and you somehow know how to use an API to create a payment link yet can't call the function itself
I wouldn't recommend w3school, This is better and more in depth
will use this in future don't think it mattered what I sent him tho lmao.
How so?
I wouldn't question someones curiosity due to past behavior or/and experiences
huh?
Atleast give good info to everyone no matter if the user shows interest or not
i mean the link i sent shows and describes the proper way to def and call a function. yet he "already" knew how to create a function just didn't know how to call it.
Ok and that has what to do what with my point?
With all due respect I'm not sure what your point was, can you re word it?
you just said give good info no matter if the user shows interest or not lmao. i just explained to you that what i referred him to was good info pertaining to his "issue"
Not really? You gave him a site about functions that also shows the calling of them, yes, while what i gave has an in depth talk about the calling of functions specifically? https://realpython.com/lessons/function-calls-definitions/
Python HTTP Server/Client: Remote end closed connection without response error hello who got fix for this ?
so I have this daily command that you can use every 24h, problem is the follow:
If I restart bot to make update everyone gets a free daily since timer resets... how can I fix this?
Too little information
Provide at least full traceback
@bot.slash_command(name="reroll")
async def reroll(interaction: nextcord.Interaction, channel: nextcord.TextChannel, id_ : int = nextcord.SlashOption(name="message_id", description="The giveaway message id!")):
new_message = await channel.fetch_message(id_)
users = await new_message.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
reroll_announcement = nextcord.Embed(color = 0xff2424)
reroll_announcement.set_author(name = f'The giveaway was rerolled by: {interaction.user.mention}', icon_url = 'https://media.discordapp.net/attachments/1007641111776481371/1008627898846027836/noadgifdev.gif')
reroll_announcement.add_field(name = f'New Winner:', value = f'{winner.mention}', inline = False)
await channel.send(embed = reroll_announcement)
if this is dpy u have to take it as a string then convert to integer
oh nextcord uhhh
its nextcord
lemme@check
okay thank you!
oh that's an Option
yea u do
yea same for nextcord
I thought that was a regular argument
oh
yea aint too much extra work tho. it's cause the size of the ints too large
yeee the inside the function just make sure u convert it to a int
its working without doing it
wait how
idk tbh loll
lmaoo hmm
BUT if its working lets just keep it that way hahha
hope it wont hit me
@remind_handler.before_loop
async def before_remind_handler(self):
await self.bot.wait_until_ready()```
AttributeError: module 'discord.ext.commands.bot' has no attribute 'wait_until_ready'
here's the code
this appears after i stop the bot
what ru doing w discord.ext.commands.bot
Do i must use (interaction) function parameter instead of (ctx) in discord 2.0 ?
Interactions are used in app commands, but if you're using text commands, you can still use ctx
^!
anyone that's got good knowledge of how error handlers work and whats possible with them? i need help in private to make my error handler like i want but i have no idea how to get any further
Like
@kick.error
no
Oh
like global error handlers used for every error it can give
I'm basically trying to make it so every error gets the same embed with the same layout, but for every error/missing argument or something it just creates the message its supposed to and then send the message
!d discord.Client.on_error
await on_error(event_method, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default error handler provided by the client.
By default this logs to the library logger however it could be overridden to have a different implementation. Check [`on_error()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_error "discord.on_error") for more details.
Changed in version 2.0: `event_method` parameter is now positional-only and instead of writing to `sys.stderr` it logs instead.
https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612
Maybe that could help?
Simple Error Handling for ext.commands - discord.py - error_handler.py
To learn smt from that
Let's read it through
Thank you for the answer.
If i use discord.py version of slash command, then must i use interaction parameter right?
it is better practice to yes so you don't confuse the two
It doesn't seem to work
slash command or ctx cmd?
Ctx
ctx.author.id
Oh
Ty
You could also use typehinting:
@tree.command()
async def help(i: discord.Interaction):```
way better btw
how do you say user = discord.get.utils = (interaction.user)
nice variable naming
Btw, I don't see a need in a help command for slash commands, but whatever
๐
how do you define the user that clicked the slash command is what i mean
.utils(discord.Member, id=123234345)
!d discord.Interaction.user
The user or member that sent the interaction.
there's no role of utils in there
thx
yayyyy, I finally found something that seems to work with this stupid lib
yeah i hate this lib
is there a way to return the number of messages that a user has sent?
like i want to greet people when they send their first message
in a channel, yes
in the server also yes, but its a bit complex
!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...
Hey
like dis?
async for message in channel.history(limit=None):
if message = 0:
await (f"Hello {interaction.user}")
me??
anybody
can u help me pls
i am getting some issue while running simple command
post the code
this is settings.py
this is main.py
when i run it it shows none
but its suppose to show me data from .env file
thats my token
is it because you spellled secret wrong?
oh ok
its not english
hmm
from python_settings import settings
from . import settings as my_local_settings
settings.configure(my_local_settings) # configure() receives a python module
assert settings.configured # now you are set
Are you sure that environment variable exist?
!d os.getenv
os.getenv(key, default=None)```
Return the value of the environment variable *key* as a string if it exists, or *default* if it doesnโt. *key* is a string. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3/library/intro.html#availability): Unix, Windows.
you're importing it wrong
no he isn't
from python_settings import settings
from . import settings as my_local_settings
settings.configure(my_local_settings) # configure() receives a python module
assert settings.configured # now you are set
he is importing fine
To check if more than 24 hours and less than 48 hours passed since you successfully called a certain command, is there a special way for that?
how are u storing the variable? like
TOKEN= "asdfasdfgh"
or
TOKEN = asldfhasdf
Or should I just do it with datetime?
use cooldown
"" like this
it dosent matter
I want to make a streak system would that work with it?
And any articles on that?
yea just each time the cmd is used store the user's id somewhere
the tut guy was like thsi and got the token
it is
well its not working so try without quotes. i don't use quotes
oke let me try
i do the exact format as you.
nope not working in my case
# settings.py
import os
from dotenv import load_dotenv
def get_token() -> None | str:
load_dotenv('.env')
return os.getenv('TOKEN') #MAKE SURE SPELLING IS RIGHT
# main.py
from settings import get_token
print(get_token())
ur doing the exact same thing he is doing but adding extra steps
i don't even see the point of having a settings.py for token
most ppl use a similar system to store variables
welcomerole = discord.utils.get(guild.roles, name="978169169013002240")
what do you think
nm
im not sure what the guild.roles does
[i for i in guild.roles if i.id = 1234][0]
who names their role same as role id 
yea so use id= not name=
still
@bot.event
async def on_member_join(member, interaction: discord.Interaction):
if member.guild.id !=935395948727779328:
return
welcomerole = discord.utils.get(guild.roles, id=978169169013002240)
await member.add_roles(welcomerole)
channel = bot.get_channel(1034633261516853390)
await channel.send(f"Welcome {interaction.user}")
oh my bad
ahhh
@topaz helm
drink some water everybody
stay hydrated
hello guys
i'm working with a scheduled event object for a discord_bot, all the attributes provided for scheduled_events does not contain a time_posted. I can use a datetime.now() when i get the event with on_scheduled_event_create event but its not so clean, is there any cleaner way to have this done
there is a start_time for scheduled events
doesn't that render when the event is going to start
yeah there is no other time attributes other than end_time
and not when the event was published
that doesn't exist
this is the only way
so i can only do a work around for it
yup
okay, thanks
Guys
How do i make an invites command like its taking on_member_join but idk hiw do i act do it and didnt find a tutorial
im sure github has code, there is no easy way to do it
oh
thanks
actually i think someone made a dpy extension specifically for that
Here?
nvm that is outdated as shit
it was disnake i was thinking of . but just search github for discord py invite tracker you'll find alot of examples
Oh thanks
neither disnake has something to handle invites lmao
yes it does i literally use it
in the API there is nothing that let you track the invites
yeah but i think that you are confusing things lmao
disnake has an Invite object but it doesn't handle people who join through that invite
bro what no i am not someone made a seperate lib, an extension using the disnake lib to track invites
lmao ok
from disnake.ext.invitetracker import InviteLogger
from lib.db import db
from lib.bot import bot
invite = InviteLogger(bot)
class Invites(Cog):
def __init__(self, bot):
self.bot = bot
@Cog.listener()
async def on_member_join(self, member: disnake.Member):
db.execute("INSERT OR IGNORE INTO members (userid) VALUES (?)", member.id)
db.commit()
data: disnake.Invite = await invite.get_invite(member)
db.execute("UPDATE members SET invites = invites + ? WHERE userid = ?", 1, data.inviter.id)
db.commit()
like i said I quite literally use it dude
btw it is easy in the end
Just check between all active invites which one uses count increase lmao
does this look right?
@discord.ui.button(label= "Click me!", style=discord.Buttonstyle.blurple, emoji=":wave:")
async def click_me(button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You clicked me!")
no i need a tree command that brings up the view huh?
i hope im on the right track
i can't understand docs so i have to piece together what other people are doing in videos
and the help i get in here
what is better? next cord or discord py v2
dpy v2
hey sarth what do you think about htiis
class MyBot(discord.Client):
def __init__(self) -> None:
super().__init__(intents=discord.Intents.all())
self.synced = False
async def on_ready():
print("Logged in")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} commands")
except Exception as e:
print(e)
bot = MyBot()
purty huh
examples/app_commands/basic.py lines 25 to 29
async def setup_hook(self):
# This copies the global commands over to your guild.
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)```
omg
god bless you
so llike this then
this says MyBot() has no attribute 'tree'
import discord
from discord.ext import commands
class MyBot(discord.Client):
def __init__(self) -> None:
super().__init__(intents=discord.Intents.all())
async def on_ready():
print("Logged in")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} commands")
except Exception as e:
print(e)
bot = MyBot()
@bot.tree.command(name = "hello")
async def hello(interaction: discord.Interaction):
# user = discord.Interaction.user
await interaction.response.send_message(f"Hello!")
examples/app_commands/basic.py lines 13 to 20
# A CommandTree is a special type that holds all the application command
# state required to make it work. This is a separate class because it
# allows all the extra state to be opt-in.
# Whenever you want to work with application commands, your tree is used
# to store and work with them.
# Note: When using commands.Bot instead of discord.Client, the bot will
# maintain its own tree instead.
self.tree = app_commands.CommandTree(self)```
What are you trying to do
im getting this error
File "/home/deusopus/Desktop/mr_bud.py", line 14, in setup_hook
self.tree.copy_global_to(guild=MY_GUILD)
AttributeError: 'MyBot' object has no attribute 'tree'
so i need to give it an attribute of tree
where do attributes live?
I just sent you the example minutes ago
my bad
Traceback (most recent call last):
File "/home/deusopus/Desktop/mr_bud.py", line 18, in <module>
self.tree = app_commands.CommandTree(self)
NameError: name 'self' is not defined
yes help you i may
Where did you put that
class MyBot(discord.Client):
def __init__(self) -> None:
super().__init__(intents=discord.Intents.all())
async def on_ready(self):
print("Logged on as {0}!".format(self.user))
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
client = MyBot()
self.tree = app_commands.CommandTree(self)
Don't just copy and paste
i dont
examples/app_commands/basic.py lines 13 to 20
# A CommandTree is a special type that holds all the application command
# state required to make it work. This is a separate class because it
# allows all the extra state to be opt-in.
# Whenever you want to work with application commands, your tree is used
# to store and work with them.
# Note: When using commands.Bot instead of discord.Client, the bot will
# maintain its own tree instead.
self.tree = app_commands.CommandTree(self)```
i kinda do
Go into that link
async def setup_hook(self):
await self.tree.sync()
import discord
from discord import app_commands
MY_GUILD = discord.Object(id=935395948727779328)
class MyBot(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.default()
client = MyBot(intents=intents)
@client.event
async def on_ready():
print(f'Logged in as {client.user} (ID: {client.user.id})')
print('------')
@client.tree.command(name = "hello", description="greeting")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message(f"Hello!")
@client.tree.command(name = "lets-goooooo", description="the battle cry")
async def letsgo(interaction: discord.Interaction):
await interaction.response.send_message(f"Let's goooooo!")
@client.tree.command(name = "to-the-mooon", description="the motto")
async def tothemoon(interaction: discord.Interaction):
await interaction.response.send_message(f"To the moooon!")
@client.tree.command(name = "button", description="generic button")
async def button(interaction: discord.Interaction):
await interaction.response.send_message(f"button button button")
there we go that link was very helpful
thank you so much
now im working on making buttons
Hi all Im having a problem, I want the bot to send a message at a certain time of the day but it doesnt work I'm not even sure if the code is correct, any one can help me plz
when I run it also without any errors O.o
you didn't start the task
You made task but didn't start lol
ok thank a lot, I will try
okay so where is a good example of buttons using that template i posted
i cant believe my memory
how do you mention a member or user without defining member or user
await interaction.response.send_message(f"Hello! Welcome {member.mention}")
is not working
nm
guys help pls. My imports are not working
are you using pycharm? even if not check if you're using a venv
hmmm
i would like to make a button that people can click
i wonder if there is a good tutorial that fits into what i have learned already
this?
await interaction.response.send_message(f'{interaction.user.mention}')
U need to install them
no i figured it out when i read it over hahaha
await interaction.response.send_message(f"Hello! Welcome {interaction.user}")
here is the whole bot https://github.com/grasshaussoftware/discord-bot.py/blob/main/general-purpose.py
various discord.py projects. Contribute to grasshaussoftware/discord-bot.py development by creating an account on GitHub.
How do I use a select menu inside a cog?
you use it
How do you get the first reactions from a message?
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
never thought about it
so how about if you want to say if member has role then do something else.....
if member.role is
if member.role not
if user.role not
i don't now
if type(client.role)?
role = discord.utils.get(message.server.roles, name=entered_team)
basically, you'll need a member object first and then access the member's roles using the roles property and check if the member has the role or not
member: discord.Member
''' searching using a Role object '''
guild = bot.get_guild(guild_id)
role = guild.get_role(role_id)
if role in member.roles:
# do something
# -------------------------------------
''' searhing by name '''
role_names = [role.name for role in member.roles]
if 'rolename' in role_names:
# do something
# -------------------------------------
''' searching by an id '''
role_ids = [role.id for role in member.roles]
if 12345654321 in role_ids: #random characters is the role id here
# do something
god bless you
๐ you're the god, bless me
blesseth be
๐
!d discord.Member.get_role
get_role(role_id, /)```
Returns a role with the given ID from roles which the member has.
New in version 2.0.
The best new emoji is ๐ซฆ
tf is this ๐
๐
my humour level is too out of league for the people here ngl
๐ like anything wtf
can someone help me?
Delete one space in front of else statement
so kinda like this.... if guild.get_role(mod_role) is None:?
Make sure they're in the same indent level
async def play(ctx: interactions.CommandContext, query: str):
queue = []
if not discord.VoiceClient[0].is_connected():
await discord.VoiceClient[0].connect()```
TypeError: 'type' object is not subscriptable
what's the matter?
now I have other errors
mention me plz
bot is undefined. What can I say ๐ซ
and how could I solve the order to go? or do you have one for mute please?
if interaction.guild.get_role(mod_role) is None:
await interaction.user.add_roles(mod_role)
await interaction.response.send_message(f"I have given you {client.role.mention}!", ephemeral = True)
else:
if interaction.guild.get_role(mod_role) is not None:
await interaction.response.send_message(f"You don't need {client.role.mention}!", ephemeral = True)
i think that works
logiccally
It really doesn't make sense
well it works except for the client.role.mention
how do you mention the role that was just given
or i could just cut out the middleman and say you got it or you didn't
just flat out
Because it works doesn't mean its logic can be optimized or changed
class button_view(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
@discord.ui.button(label = "Get Moderator Role, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.guild.get_role(mod_role) is None:
await interaction.user.add_roles(mod_role)
await interaction.response.send_message(f"I have given you {client.role.mention}!", ephemeral = True)
else:
if interaction.guild.get_role(mod_role) is not None:
await interaction.response.send_message(f"You don't need {client.role.mention}!", ephemeral = True)
@client.tree.command(guild=MY_GUILD, name = 'get-mod-perms', description='Get moderator permissions!')
async def launch_button(interaction: discord.Interaction):
await interaction.response.send_message(view = button_view())
it's that {client.role.mention} that needs fixed
Just add the role and use EAFP
!d EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
!d LBYL
Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.
In a multi-threaded environment, the LBYL approach can risk introducing a race condition between โthe lookingโ and โthe leapingโ. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.
that doesn't apply necessarily
as you can see i have an if statement that looks for their existing role
if the moderator role is non existent ie None then it grants them the moderator role
if interaction.guild.get_role(mod_role) is None:
await interaction.user.add_roles(mod_role)
if they don't have mod role give them mod role
then
if interaction.guild.get_role(mod_role) is not None:
await interaction.response.send_message(f"You don't need {client.role.mention}!", ephemeral = True)
pretty colors
trying to get help loll
even if im ending the giveaway
its not rlly ending it
no but it was after it
you totally scrolled my convo though bro
What's the problem
How so?
its not ending it
as i was saying
just sending that it ended but it didnt rlly
please scroll back
i could just flat out say they got the mod role or they don't need the mod role either way
i don't need to pull the role
The thing is your logic in your code doesnt make sense, you're checking if the role is in cache not in the author๐ค
how do i check the author
You can use EAFP or LBYL
Yes
How so?
i know what you are saying but it's too simple
And the problem being?
user.roles
how to mention the role that was just given in a message
await interaction.response.send_message(f"You don't need {client.role.mention}!", ephemeral = True)
like how do i make that say "You don't need the moderator role"
with formatting of the call to roles
helpp
^
does anyone know why it doesn't work? it's correct? when I try to test, nothing happens
why do u need self
{interaction.user.role.mention}
because you have to instantiate itself as an object
I didn't really understand
oh okay
me, you, them
When the European Association of Fish Pathologists
Lesbian Basketball Youth League
@slate swan how can I make it work?
with a little help from your friends
can u send the whole code
of course I'll also send you unwarn, is that ok?
ofc
i like my code hot off the grill
!paste
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.
When I get home imma sudo do-release-upgrade
@commands.command()
@commands.has_permissions(manage_messages=True)
async def warn(self, ctx, member: discord.Member, * , reason = None):
em = discord.embed(title = "Member Warned!" , description = f'{member} was been warned for: {reason}', colour = discord.Colour.random())
await ctx.send(embed = em)
@commands.command()
@commands.has_permissions(manage_messages=True)
async def unwarn(self, ctx, member: discord.Member):
em = discord.embed(title = "Member Warned!" , description = f'{member} was been warned', colour = discord.Colour.random())
await ctx.send(embed = em)
@slate swan
let's code some python girls and guys
member.mention
Yes let's code a snake
where can i get it?
Ah yes finally
I put it but it's still the same, it doesn't do anything
show error
there are no errors in the console
so when i do the end command its not really ending, yes its sending a winner but it should look like that when i end that
what r ur imports
I don't really know what you mean
is that ur whole code?
His issues arent due to imports or attributes it seems like he's using commands.command to register commands when he's not inside a cog, from the look of indentation
yes
๐ง
OH WAIT JUST SAW
also for warn/unwarn

use @bot.command() instead of @commands.command
ok
and remove self
like i said
also can someone help
This is the story of how a man outside of cog thought he is inside
now there are errors
wait wair
๐ค
can u send the whole pic of ur code(just not the token)
client variable naming lol
of course I received you privately that there are a little more
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 know it was named for a british comedy group from the 80s
something like Mrs. Python or something
1960s - 2000s
i know i was just playing
Monty Python!
did you throw up?
Ok
I don't like SPAM
Now for something completely different
Bicycle Repairman
that's a good one
bruh
!e
def repairman(bicycle):
return bicycle
print(repairman(1))
@alpine cove :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
so when i do the end command its not really ending, yes its sending a winner but it should look like that when i end that
possibly a stupid question but looping through every message since the start of the month in my server to check how many times a keyword was said by each user?
possibility of being banned?
i did what i was trying to do
await interaction.response.send_message(f"I have given you {interaction.user.get_role(979353319644479559)}!", ephemeral = True)
how can i make a form tab like this ?
modals?
?
yes thanku
smart_Switch_Off = Button(label = "OFF", style = discord.ButtonStyle.red)
# discord channel switch on button
async def smart_switch_on_callback(interaction):
await interaction.response.defer()
await msg.edit(embed=switch_On_Embed)
print(f"{msg.author.name}")
# discord channel switch off button
async def smart_switch_off_callback(interaction):
await interaction.response.defer()
await msg.edit(embed=switch_Off_Embed)
# button callback
smart_Switch_On.callback = smart_switch_on_callback
smart_Switch_Off.callback = smart_switch_off_callback
view = View(timeout=None)
view.add_item(smart_Switch_On)
view.add_item(smart_Switch_Off)
How do I know the name of the user who clicked the button?
!d discord.Interaction.user
The user or member that sent the interaction.
The userโs username.
so when i do the end command its not really ending, yes its sending a winner but it should look like that when i end that
i wish i could figure out how to give someone a role when they press a button
i got this so far
letme help u
thanks buddy
@discord.ui.button(label = "Get OG Status, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.get_role(985708739392839720) is None:
await interaction.user.add_roles(interaction.user.role(985708739392839720), reason=reason )
await interaction.response.send_message(f"I have given you {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
else:
if interaction.user.get_role(985708739392839720) is not None:
await interaction.response.send_message(f"You don't need {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
i just need the line about adding the role to the person that clicked the button everything else works
oh yeah i do
send it all
class button_view(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
@discord.ui.button(label = "Get OG Status, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.get_role(985708739392839720) is None:
await interaction.user.add_roles(the struggle is real)
await interaction.response.send_message(f"I have given you {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
else:
if interaction.user.get_role(985708739392839720) is not None:
await interaction.response.send_message(f"You don't need {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
@client.tree.command(guild=MY_GUILD, name = 'get-og-status', description='Get OG status!') #guild specific slash command
async def launch_button(interaction: discord.Interaction):
await interaction.response.send_message(view = button_view())
make the class that way
class button_view(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.value = None
self.timeout = None```
Any errors?

Why does he need to do that?
yeah
What for?
discord.utils.get(interaction.guild.roles, name="the name or the id instead of name")
for getting the role
His way is fine..?
ok
.get_role() is preferred anyway
I prefer getch 
ive been close
hey
i am using args and ctx command to get a message form user
now the message is multi line
and i wana store it same as it is
any idea how can i do it
@south coyote Could you tell us the problem? Right now we're just assuming.
@cloud dawn can u help w that?
you don't need to do anything special for that
so wht am i suppose to do
one sec
Honestly a giveaway command is hard, I recommend starting simple, It has some mistakes in the code and some old methods.
if you mean that all part of the message is not getting consumed you need to add a consume rest argument py async def command(context, *, argument) -> Any: argument will take everything that comes after !command
oke
oh okay thanks!
If you do still want help the current question is kind of vague "look like that when I end that", I don't know what you mean.
What should it do when it reaches the end?
class button_view(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.value = None
self.timeout = None
@discord.ui.button(label = "Get OG Status, Now!", style = discord.ButtonStyle.green, custom_id = "role_button")
async def get_mod(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.get_role(985708739392839720) is None:
role = discord.utils.get(interaction.guild.roles, name="985708739392839720")
await interaction.user.add_roles(role)
await interaction.response.send_message(f"I have given you {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
else:
if interaction.user.get_role(985708739392839720) is not None:
await interaction.response.send_message(f"You don't need {interaction.user.get_role(985708739392839720)}!", ephemeral = True)
@client.tree.command(guild=MY_GUILD, name = 'get-og-status', description='Get OG status!') #guild specific slash command
async def launch_button(interaction: discord.Interaction):
await interaction.response.send_message(view = button_view())
Um actually, your's naming convention is sucks ๐ค
thank u verymuch it really workedd
