#discord-bots

1 messages ยท Page 697 of 1

velvet tinsel
#

nice phone btw ๐Ÿ˜

#

is that SAMSUNG?

boreal ravine
#

no

velvet tinsel
#

oh

#

then what is it

#

looks hot

tawdry perch
#

Very relevant to this channel

#

Is it possible to limit commands to specific prefix?

heavy folio
#

wdym

tawdry perch
#

If bot has prefixes ! And ? As example, would it be possible to have different commands for that ? Prefix

velvet tinsel
#

but you can have multiple prefixes

slate swan
#

!d discord.ext.commands.Context.prefix

unkempt canyonBOT
velvet tinsel
#

im gonna go ahead and ask stack overflow actually

tawdry perch
#

That would be useful, I can make custom decorator for that

slate swan
#

yea

tawdry perch
#

I can just put the prefix to deco and that's it

#

Thank you!

velvet tinsel
#

I asked it on SO

#

wish me luck ๐Ÿ˜”

tawdry perch
#

Gl, you will get hated with 99% change

#

0.2 % change to get help and other 0.8 is mystery

velvet tinsel
#

yeah, I get like -100 downvotes each time

why ๐Ÿ˜ญ

#

pog

#

I just gained 2 rep for editing

slim dragon
#

guys I found the problem in my code

#

hahaha

#

I'm soo stupid

velvet tinsel
#

? what was the solution?

velvet tinsel
slim dragon
# velvet tinsel ? what was the solution?

actually I've to update my .db file with all my existing commands... so If any command exist in the database then only the command will work else bot will say no such command

#

hahaha

tiny ibex
#

How to solve this dumb issue

slim dragon
#

so i added this b.se command to my database file and then I think it should work

upbeat otter
slate swan
#

basically , his ' character shows up as ’

#

just use replace?

untold token
#

Because that looks like html jargon

tiny ibex
#

So how to convert html entities in text

tiny ibex
austere plinth
#

Guys who know how to find out in what voice channel is the user now? I read the documentation, it says about the VoiceState, but I do not understand how to use it. Can you show on the example pls?

visual island
unkempt canyonBOT
#

@visual island :white_check_mark: Your eval job has completed with return code 0.

โ€™
slate swan
#

nvm you already got the answer

velvet tinsel
#

Web scrapping

#

๐Ÿ˜ญ

tough isle
#

at least say what the project is

#

no stranger is gonna write your bot, just because

slate swan
#

ah wait

maiden fable
#

U can simply do member.send BTW

slate swan
#

How do I make my bot dm the user who invited the bot

opal skiff
#

on_member_join event```py
await member.dm_channel.send(embed=nextcord.Embed(description="Willkommen auf "+str(member.guild)+"!",color=0x206694).set_image(url=nextcord.Client.get_guild(member.guild.id).icon.url))

```TypeError: Client.get_guild() missing 1 required positional argument: 'id'```
slate swan
#

on_member_join has attribute (guild)

#

just replace with guild

opal skiff
#

like py on_member_join(member,guild)?

slate swan
#

nah

#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
slate swan
#
@client.event
async def on_guild_join(guild):
  #do something```
opal skiff
#

hmm i dont think this will work

slate swan
#

You want to dm a member?

opal skiff
#

yes

slate swan
#

DM who?

opal skiff
#

the joining member

slate swan
#

When someone join, you want your bot to dm him/her?

opal skiff
#

yes

slate swan
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
opal skiff
#

and i want the icon of the server the member joined

slate swan
tawdry perch
#

Finally!

opal skiff
#

nextcord

slate swan
opal skiff
tough isle
#

oh ok

sage otter
#

I have no idea why you make a cache lookup to grab the guild when you literally already have it with Member.guild

#

If you want the icon. Itโ€™s literally just
Member.guild.icon.url

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

Guys How do I dm the user who added the bot to the channel??
ruby lion
#

how to get the guild name in the 'on_message' function?

slate swan
#

I want to do it using integrations

slate swan
hollow plover
#

hello, i just started using discord.py 2..0 or whatever but i am pretty familiar wth 1.7 or something. now when i use one of my commands it says hello, i just started using discord.py 2..0 or whatever but i am pretty familiar wth 1.7 or something. now when i use one of my commands it says Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url what should i change it to

#

pls ping me

tawdry perch
#

avatar.url

hollow plover
#

ok

#

thanks, i will try this.

lunar quail
#
def blockify(given_text : str):
    given_text = given_text.lower()
    # ^ Just incase it was uppercase, feel free to remove.
    text_to_block_dict = {
        letter : uni_emoji for (letter, uni_emoji) in zip(
            [chr(ltr) for ltr in range(ord("a"), ord("z") + 1)],
            [chr(uni_emo) for uni_emo in range(127462 , 127487 + 1)]
        )
    }
    return "".join([
        text_to_block_dict[f] for f in given_text
    ])
cinder horizon
#

can anyone gimme an example or reference to slicing an embed coz lyrics command be giving me 4000+ characters....

manic wing
cinder horizon
sage otter
#

You can use something like textwrap.wrap() for chunking the string into a list of smaller strings

#

!d textwrap.wrap

unkempt canyonBOT
#
textwrap.wrap(text, width=70, *, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, ...)```
Wraps the single paragraph in *text* (a string) so every line is at most *width* characters long. Returns a list of output lines, without final newlines.

Optional keyword arguments correspond to the instance attributes of [`TextWrapper`](https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper "textwrap.TextWrapper"), documented below.

See the [`TextWrapper.wrap()`](https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper.wrap "textwrap.TextWrapper.wrap") method for additional details on how [`wrap()`](https://docs.python.org/3/library/textwrap.html#textwrap.wrap "textwrap.wrap") behaves.
sage otter
#

???? I was pulling it up for him? Did you not read anything I said?

cinder horizon
tiny ibex
#

Nvm I just couldn't find bot-commands so I mentioned it to find it๐Ÿ˜…

#

Lost it again

#

#bot-commands

sage otter
#

If you need a paginator you can make one yourself or see one online.

sage otter
#

I actually saw one on pypi yesterday that was pretty easy to use

#

!pypi EZPaginator

unkempt canyonBOT
quaint epoch
#

hey anyone know how to get verified users emails?

#

how can i check if they are verified and get this email?

#

oh nvm

#

i need oauth2

slate swan
gritty fiber
#

Hey, so I thought about creating a feature on my bot that counts the messages people send in a specific period of time and gives them a role if they achieve some kind of goal. But it should only work for people that have reacted to a specific message. So does anyone have ideas on how to start this?

quaint epoch
manic wing
#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.webhooks "discord.Guild.webhooks") and [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"). The ones received by the library will automatically be bound using the libraryโ€™s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.7)"):
manic wing
#

is this 2.0

manic wing
#

fuck where did it go

gritty fiber
manic wing
#

damnit

cloud dawn
manic wing
#

anyone know where AsyncWebhookAdapter went?

tawdry perch
#

Uh

#

I think it's gone

manic wing
#

oh turns out i dont even need it

tawdry perch
#

It was removed, let me check my code

gritty fiber
cloud dawn
hollow plover
#

using discord.ui.Button, how do you check which button they press with button.callback?

#

please ping me on respoonse, thx

hybrid fjord
#

can someone link me an article or doc on how to implement the timeout feature

hollow plover
#

discord.errors.ExtensionFailed: Extension 'cogs.utility' raised an error: TypeError: 'Button' object is not callable Please explain?!?!?!

manic wing
#

well it might be nice if you showed what Button is and what you're trying to call pithink

hollow plover
#

Button is probably discord.ui.Button

#

and i think im trying to call this:

#

because without this it works

hollow plover
#

also pls ping me when respond because i have to go now ill check messages later

hybrid fjord
#

any

slate swan
#

!d discord.ui.button

unkempt canyonBOT
#

discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
slate swan
#

Yeah

final iron
#

Ghost ping, very cool

hybrid fjord
#

in case you hadn't seen it

tawdry perch
potent citrus
#

!d discord.ui.button

unkempt canyonBOT
#

discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
hybrid fjord
#

can you give me any sort of guidance on how to use it

potent citrus
#

try:
loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
loop.run_until_complete(close())
# cancel all tasks lingering
finally:
loop.close()

tawdry perch
#

I have not yet tested this because I have no idea how to get 2.3

#

But I would guess you get member object and do member.timeout(duration, reason)

#

if you have a idea how to upgrade to 2.3 ping me

slate swan
#

await bot.process_commands(message)
gives error
AttributeError: 'NoneType' object has no attribute 'id'

manic wing
slate swan
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 178, in on_message
    await bot.process_commands(message)
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 975, in process_commands
    ctx = await self.get_context(message)
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 883, in get_context
    if self._skip_check(message.author.id, self.user.id):
AttributeError: 'NoneType' object has no attribute 'id'

^

steep estuary
#

how i can ban a member who is not in my server ?

manic wing
potent citrus
#

'''''psy '''print (hello world)

slate swan
#

<Message id=922878058749370398 channel=<TextChannel id=922865149105303622 name='d' position=17 nsfw=True news=False category_id=921064299001176107> type=<MessageType.default: 0> author=<Member id=535319856913055744 name='ADX' discriminator='5452' bot=False nick=None guild=<Guild id=921064299001176106 name="ADX's server" shard_id=None chunked=False member_count=2>> flags=<MessageFlags value=0>> <class 'discord.message.Message'>
@manic wing

manic wing
#

odd..

#

show the code around it

slate swan
#
@client.event
async def on_message(message):
    print(message, type(message))
    await bot.process_commands(message)

here the start of the on_message (everything else after this works

here the command

#

fuck it has a invite lol

manic wing
#

err

slate swan
#
@bot.command()
async def helpcmd(ctx):
    print("debug\nd"*100)
    embed = discord.Embed(title="> __A-NSFW__", description=ctx.author.mention, color=0xFFC0CB)
    embed.add_field(name="a!start: ", value="```Use this commmand in any NSFW channel, to start Auto-NSFW.```", inline=False)
    embed.add_field(name="a!stop: ", value="```Use this commmand in any channel, to stop Auto-NSFW.```", inline=False)
    embed.add_field(name="a!ping: ", value="```Use this commmand in any channel, to check the latency of the bot.```", inline=False)
    embed.add_field(name="Author: ", value="```ADX#5452```")

    embed.set_footer(text="Support:  adx@adxservers.xyz, ADX#5452")
    await ctx.send(content=None, embed=embed)
unkempt canyonBOT
#

await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
manic wing
#

client and bot?

slate swan
#

I got a warning lol

#

And typehint the user param to discord.User instead of discord.Member @steep estuary

steep estuary
#

how i can ban a member who is not in my server ?

manic wing
#

a client and a bot

slate swan
#

idk

quick gust
sage otter
slate swan
#

I started with client and changed to bot later lol

manic wing
#

thats prob why its erroring

slate swan
#

shouldnt be

slate swan
sage otter
#

Oh. Didnโ€™t know AMshrug

slate swan
#

Because I'm pretty sure they're also snowflake objects, i could be wrong since I don't really look at the source code sus

#

Regardless, from my own experience, if works ASakashrug

sage otter
#

Interesting AYS_pepehmm

slate swan
#

how do I override

โ€‹No Category:
  help    Shows this message
  helpcmd 

Type a!help command for more info on a command.
You can also type a!help category for more info on a category.```
#

im trying to make a helpcmd and this

#

is a problem

#

can I add help_command=help

#

in bot

#

or smthing like that

manic wing
#

help_command=None and then you can just make a help command

slate swan
#

ok

manic wing
#

unless you want to subclass it....

#

which i dont recommend for a beginner

quick gust
tawdry perch
#

there is great tutorial for subclass stuff in pinned messages tho

steep estuary
slate swan
#

That ain't what I gave you

#

ctx.guild.ban(user)

graceful mulch
#

and all File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

slate swan
#

It's an awaitable, don't forget about that ASakashrug

steep estuary
# slate swan It's an awaitable, don't forget about that <:ASakashrug:865101449834659881>
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: Optional[discord.Member]=None, days: Optional[int]=None, *, reason:Optional[str]=None):
    if ctx.author.guild_permissions.ban_members:
        if member is not None:
            if days is not None:
                wait = days * 86400
                try:
                    embed = discord.Embed(description = f"** {member.mention} has been Banned Successfully by {ctx.author.mention} for `{days}` Days **" if reason is None else f"** {member.mention} has been Banned Successfully by {ctx.author.mention} for `{days}` Days \n\t With the Reason of :\t{reason}**",color=embedTheme)
                    dmuser = discord.Embed(description = f"** You are Banned by {ctx.author} from {ctx.guild.name} for `{days}` Days **" if reason is None else f"** You are Banned by {ctx.author} from {ctx.guild.name} for `{days}` Days \n\t With the Reason of :\t{reason}**",color=embedTheme)
                    await ctx.send(embed=embed)
                    member = await bot.fetch_user(member.id)
                    await member.ban(reason=reason)
                    await member.send(embed=dmuser)
                    await modlogs(ctx, "Ban", member, ctx.author, f"{days} Day(s)" , reason, "Banned")
                    await asyncio.sleep(wait)
                    await ctx.guild.unban(member)
                    await modlogs(ctx, "Unban", member, bot.user, None, "Auto", "Unbanned")
                except Exception as e:
                    print(f"Exception - {e}")
                    await ctx.reply(f":exclamation: Failed to Ban {member} From {ctx.guild}")
```this is code
#

when i use member: discord.Member this only bans the user which is in the ctx.guild

graceful mulch
#

yes

steep estuary
#

and member: discord.User gives error Exception - 'User' object has no attribute 'ban'

graceful mulch
#

ofcu cant ban any discord.user

slate swan
steep estuary
steep estuary
#

srry i didn't focused on it

slate swan
graceful mulch
#

no code

#

it is decoder

#

i didnt used any json file

#

with this namesee

#

the path

steep estuary
#

?

graceful mulch
#

discord.Member

steep estuary
#

ohk

slate swan
tawdry perch
#

discord.User for non guild

slate swan
#

^

graceful mulch
#

Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 2818, in on_message
users = json.load(f)
File "/usr/lib/python3.8/json/init.py", line 293, in load
return loads(fp.read(),
File "/usr/lib/python3.8/json/init.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

steep estuary
final iron
steep estuary
#

discord.User?

graceful mulch
graceful mulch
#

oh wait

slate swan
graceful mulch
#

let me show you

#
172.18.0.1 - - [21/Dec/2021 16:03:39] "GET / HTTP/1.1" 200 -
Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 2818, in on_message
    users = json.load(f)
  File "/usr/lib/python3.8/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
#

full error

slate swan
#

Does your json file have {}

maiden fable
#

{}

graceful mulch
#

had

slate swan
#

Although as I said, the first step, is to not use json, but a database instead

graceful mulch
#

nowi deleted all data and addded brackets

#
172.18.0.1 - - [21/Dec/2021 16:03:39] "GET / HTTP/1.1" 200 -
Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 2818, in on_message
    users = json.load(f)
  File "/usr/lib/python3.8/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
hybrid fjord
#

can someone link me an article or doc on how to implement the timeout feature

unkempt canyonBOT
#

When using JSON, you might run into the following error:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This error could have appeared because you just created the JSON file and there is nothing in it at the moment.

Whilst having empty data is no problem, the file itself may never be completely empty.

You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.

Different data types are also supported. If you wish to read more on these, please refer to this article.

hybrid fjord
#

ok thanks

slate swan
#

It's barely been released to discord, so be patient

graceful mulch
# manic wing !json

@client.event
async def on_message(message):

if not message.author.bot:

    with open('level.json','r') as f:
        users = json.load(f)

    await update_data(users, message.author,message.guild)
    await add_experience(users, message.author, 4, message.guild)
    await level_up(users, message.author,message.channel, message.guild)

    with open('level.json','w') as f:
        json.dump(users, f)
    msg = message.content  
    for word in filter:

      if word in msg:
        
        await message.delete()



if message.author in afkdict:
  afkdict.pop(message.author)

for member in message.mentions:  
    if member != message.author:  
        if member in afkdict:  
            afkmsg = afkdict[member]  
            await message.channel.send(f"Oh noes! {member} is afk. {afkmsg}")     
await client.process_commands(message)
#

line 2818

quick gust
#

iirc someone here said disnake has added it?

slate swan
#

Disnake will pretty soon tho

manic wing
slate swan
hybrid fjord
quick gust
#

yea

slate swan
graceful mulch
#

f

#

y json empty

#

lol

hybrid fjord
#

Let me see

#

must have missed it

tawdry perch
#

It's just not yet possible to have since 2.3 is not released

tawdry perch
hybrid fjord
#

ah

#

so it's not usable right now?

slate swan
#

it is , if you use disnake

tawdry perch
#

not yet I think, maybe possible from source

tawdry perch
slate swan
#

and yea , the perms

hybrid fjord
slate swan
tawdry perch
#

so it's in github but not yet in pypi

slate swan
hybrid fjord
#

alright

twin moon
#

can I add buttons and dropdowns

quaint epoch
#

!d discord.Guild.get_member_named

unkempt canyonBOT
#

get_member_named(name, /)```
Returns the first member found that matches the name provided.

The name can have an optional discriminator argument, e.g. โ€œJake#0001โ€ or โ€œJakeโ€ will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.

If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.

If no member is found, `None` is returned.
quaint epoch
#

nice

slender perch
#

this is supposed to give info on what servers a bot is in:

token = input("token: ")
prefix = "?"

import discord
from discord.ext import commands
from discord.ext.commands import Bot

bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")


def makelink():
  async def makelink():
    invite = ctx.channel.create_invite()
    await print(f"Here's your invite: {invite}")
  
async def invite():
    invite = await message.channel.create_invite()
    print(invite)
  
@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print(discord.__version__)
    print('------')
    print('Servers connected to:')
    print('------')
    for guild in bot.guilds:
        print("invite:")
        invite()
        print("")
        print("name:")
        print(guild.name)
        print(" ")
        print("id:")
        print(guild.id)
        print(" ")
        print("owner id:")
        print(guild.owner_id)
        print(" ")
        print("member count:")
        print(guild.member_count)
        print(" ")
        print(('------'))



bot.run(token)
#

but after running, i dont get anything for invite()

#

just

#

ive been working on this for a while and want to add gui using either html5 or pygui, but this is the last thing i need to fix

slate swan
#

await it

slender perch
#

like this?

def makelink():
  async def makelink():
    invite = ctx.channel.create_invite()
    print("making invite")
    print("invite: " + invite)
  
  
@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print(discord.__version__)
    print('------')
    print('Servers connected to:')
    print('------')
    for guild in bot.guilds:
        print("invite:")
        await makelink()
lunar quail
#

you are getting an runtimeerror : didn't await xyz error right?

slender perch
#

i didnt see that before

#

but now its just showing up as nothing

#
------
invite:

name:
[name]
 
id:
[id]
 
owner id:
[id]
 
member count:
17
#

like that

slate swan
#
  File "C:\Users\  -PC\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 618, in _load_from_module_spec
    setup(self)
  File "c:\Users\  -PC\Desktop\Discord stuff\experimental bot\12(warn)\cogs\warn.py", line 31, in setup
    bot.add_cog(warn(bot))
TypeError: warn.__init__() takes 1 positional argument but 2 were given

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\  -PC\Desktop\Discord stuff\experimental bot\12(warn)\main.py", line 25, in <module>
    client.load_extension(f'cogs.{filename[:-3]}')
  File "C:\Users\  -PC\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\  -PC\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 623, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.warn' raised an error: TypeError: warn.__init__() takes 1 positional argument but 2 were given    ``` some help ![aPES2_Sweat](https://cdn.discordapp.com/emojis/525603859830407168.webp?size=128 "aPES2_Sweat")
slender perch
#

this is my entire code atm

#
token = input("token: ")
prefix = "?"

import discord
from discord.ext import commands
from discord.ext.commands import Bot

bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")


def makelink():
  async def makelink():
    invite = await ctx.channel.create_invite()
    print("making invite")
    print("invite: " + invite)
  
  
@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print(discord.__version__)
    print('------')
    print('Servers connected to:')
    print('------')
    for guild in bot.guilds:
        print("invite:")
        makelink()
        print("")
        print("name:")
        print(guild.name)
        print(" ")
        print("id:")
        print(guild.id)
        print(" ")
        print("owner id:")
        print(guild.owner_id)
        print(" ")
        print("member count:")
        print(guild.member_count)
        print(" ")
        print(('------'))



bot.run(token)
lunar quail
#

Oh I found the error

#

lemme rewrite it

torn sail
slate swan
# torn sail Could you should the code for `warn.__init__`
import discord
from discord.ext import commands
import asyncpg
import decouple

class warn(commands.Bot):
    def __init__(self,**options):
        super().__init__(
            command_prefix='e!',
            intents = discord.Intents.all(),
            case_insensitive = True
            **options)
    
        self.loop.run_until_complete(self.create_db_pool)

    async def create_db_pool(self):
        self.db = await asyncpg.create_pool(database="warn", user="postgres",password="the password")
        

def setup(bot):
    bot.add_cog(warn(bot))```
slate swan
#

Can I convert string into int ?

torn sail
#

int()

slate swan
#

Yeahh but mine code not working

torn sail
#

Show

slate swan
#

Just taking simple input and want to covert

torn sail
#

Show the code

slate swan
#

Sorry I am beginner

torn sail
# slate swan

You cannot convert โ€œabcโ€ into a int. Only numbers without a decimal

slate swan
#

abc is a string

#

And int is function to covert into int type

torn sail
#

Yeah can you make abc a number?

slate swan
#

Nah I can't

torn sail
#

Can you turn โ€12โ€ into a int but not โ€abcโ€

slate swan
#

That means int function can only covert any number into int

torn sail
#

Yes

#

And this is also the wrong channel for this

slate swan
#

Sorry new here in python community

#

@torn sail sir where is the doubt channel

tough lance
lunar quail
# slender perch ```py token = input("token: ") prefix = "?" import discord from discord.ext imp...
import discord
import os
from discord.ext import commands

bot = commands.Bot(command_prefix="?", help_command=None)

  
@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print(discord.__version__)
    print('------')
    print('Servers connected to:')
    print('------')
    for guild in bot.guilds:
        print(f"Guild name : {guild.name}")
        print(guild.id)
        print(guild.owner_id)
        print(guild.member_count)

        print("Channels and invites :")
        for each_channel in guild.channels:
            try:
                print(f"channel name : {each_channel.name} || invite : {await each_channel.create_invite()}")
            except:
                # Bot tried to access an non-existent channel
                pass
        
bot.run(os.getenv("DISCORD_TOKEN"))
slate swan
#

why does my bot randomly get killed

lunar quail
#

You can format the other strings however you want

slate swan
lunar quail
slate swan
#

nothing in logs

slate swan
lunar quail
slate swan
#

no

#

I mean im sure its not

lunar quail
tough lance
#

That's really kinda sus

lunar quail
#

Could you show us your console?

#

where it was displayed

slate swan
#

its same as if u would ctrl z

#

or kill python3

lunar quail
slate swan
#

no

lunar quail
#

the keyboard interrupt

slate swan
#

z kills

lunar quail
#

oh

slate swan
lunar quail
tough lance
#

You're subclassing commands.Bot

slate swan
#

aight gonna wait till it happens again

slate swan
slate swan
cinder fossil
slate swan
#

yes

tough lance
slate swan
#

huh

cinder fossil
#

is print("killed") anywhere in your code?

slate swan
#

no

lunar quail
#

I kinda remember this error somewhere

slate swan
#

bruh didn't mean it like its from the code, it just gets killed and it says "Killed"

#

Killed
root@servers:/home/bot/adx#

#

last message was that

#

I mean its literally just killed

lunar quail
slate swan
#

yea

lunar quail
#

but not with with open

#

and you forgot to close it?

slate swan
#

ah yes ik what the problem is now

lunar quail
#

hell yea

#

You got yourself a memory cry

#

just do yourvarname.close()

#

better yet, use a manager

#
with open (...) as ...:
    ....
slate swan
#

I usually use

try:
file.close()
except NameError:
pass

#

at the end of my code

#

so it closes every file

#

but I had removed it before for smthing

lunar quail
#
try:
    ...
except:
    ...
finally:
    ...
slate swan
#

hm actually I do have file.close already on everything

lunar quail
#

and you

try:
    ...
except:
    ...
finally:
    file.close()
slate swan
#

so that cant be the problem

lunar quail
#

Just use with open

#

why even deal with this headache

#

also it is an significantly better practice

#

and you won't get mysterious errors which just say killed

sour lodge
#

Are intents or whatever those are, required with discord.py?

torn sail
sour lodge
#

Oh ok thanks

slate swan
#

I dont know what the hell is going on with my vds / bot, its recently been using lines that are commented, and using removed code like its using a older version of my code?

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

lament mesa
lunar quail
slate swan
#

bro yall cant be srs

sour lodge
lunar quail
slate swan
#

ofc I saved @lament mesa , no @lunar quail , and yes I did @final iron

lament mesa
#

hmm

slate swan
#

also the Killed is probably bcs of
#signal(SIGPIPE,SIG_DFL)

#

which is also commented

#

cuz I was using it before

final iron
slate swan
cinder fossil
#

if server's download speed is slow or something it could be that they have a different copy of your code saved (and being executed) compared to what you see clientside

slate swan
#

no

#

cant be that either

final iron
slate swan
#

yes

unkempt canyonBOT
#

Hey @slate swan!

It looks like you tried to attach file type(s) that we do not allow (.xml). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

slate swan
#

here is my filezilla log

sour lodge
#
import discord
from discord.ext import commands
from discord import Intents

intents = Intents.default()
intents.members = True

client = commands.Bot(command_prefix = "!!", intent = intents)

@client.event
async def on_ready():
  print("Bot is ready.")

@client.event
async def on_member_join(member):
  print(f"{member} has joined a server.")

@client.event
async def on_member_remove(member):
  print(f"{member} has left a server.")
``` why does  "member has joined" and "member has left a server" not print?; ||the client.run() is there dw I just didnt include it here||
upbeat otter
sour lodge
upbeat otter
#

lol sorry

sour lodge
#

its fine

cinder fossil
cinder fossil
#

in that case try just printing str(member) + "has left the server"

final iron
cloud dawn
#

Time for disnake

slate swan
#

2021-12-21 19:46:09,672:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 59.82 seconds
2021-12-21 19:47:17,363:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 59.97 seconds
2021-12-21 19:48:25,304:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 60.00 seconds
2021-12-21 19:49:26,505:WARNING:discord.gateway: WebSocket in shard ID None is ratelimited, waiting 59.96 seconds

#

uh this in my logs

slate swan
cloud dawn
#

Oh then you are just rate limited.

slate swan
#

ah

pliant gulch
slate swan
#

yes

pliant gulch
#

There you go

#

That's the issue

slate swan
#

and im infinetly sending messages

cloud dawn
#

What would you expect..?

pliant gulch
#

change_presence sends a payload to the internal wrbsocket

#

Therefor causing the ratelimit

#

As you can only send like uhh

cloud dawn
#

1 change per 20 second ish

#

Maby even more if they find a pattern.

final iron
pliant gulch
#

It's safe to say it's at a const rate of 120/6s

#

Unlike endpoint rate limits the gateway one is fixed

#

I.e not dynamic

sour lodge
maiden fable
slate swan
#

hm

#

its like someone is sending cntrl + z

final iron
#

Do you have any eval commands or exec() in your code?

pliant gulch
#

Iโ€™d assume for presences and voice stuff or?

maiden fable
#

I am talking about updating RP

slate swan
#

!d os.remove

unkempt canyonBOT
#

os.remove(path, *, dir_fd=None)```
Remove (delete) the file *path*. If *path* is a directory, an [`IsADirectoryError`](https://docs.python.org/3/library/exceptions.html#IsADirectoryError "IsADirectoryError") is raised. Use [`rmdir()`](https://docs.python.org/3/library/os.html#os.rmdir "os.rmdir") to remove directories. If the file does not exist, a [`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError "FileNotFoundError") is raised.

This function can support [paths relative to directory descriptors](https://docs.python.org/3/library/os.html#dir-fd).

On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.

This function is semantically identical to [`unlink()`](https://docs.python.org/3/library/os.html#os.unlink "os.unlink").

Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.remove` with arguments `path`, `dir_fd`.

New in version 3.3: The *dir\_fd* argument...
vast gale
wicked atlas
vast gale
#

i 100% meant to run a command on myself

pliant gulch
#

Oh you guys see that new timeout feature from discord

#

Supperrr nice

vast gale
#

No database, persistent mutes and no tasks.loop
they aren't fully persistent

pliant gulch
#

If the user leaves and rejoins it doesn't persist?

sick birch
#

good to see discord is taking moderation into their own hands

pliant gulch
#

Basically deprecated almost most of the existing mute commands

vast gale
slender perch
#

!message

vast gale
#

ah, I misunderstood, its perma mutes

#

!d discord.Message @slender perch

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

x != y Checks if two messages are not equal.

hash(x) Returns the messageโ€™s hash.
slender perch
#

thamks

slate swan
#

Can someome Help me

pliant gulch
#

Meaning you can do all logging of mutes strictly in audit logs

slate swan
#

how do I put an " inside of "

#

I want put "+"

#

But i did It and dont work

slender perch
#

simular to my discord server checker, how would i make a program where you can message specific users specific things?

like

input token:
input userid:
input message:

and it sendsthe message input to the userid from the token

sick birch
# slate swan

!e

print("Quotes inside quotes: \"Hello, world\"")
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

Quotes inside quotes: "Hello, world"
slate swan
#

Ooooo ty

sick birch
slender perch
#

ehh sort of

#

since there is no actual client where you can log in as a bot rn, i wanted to make this to dm bot owners if there bot is vulnurable

sick birch
#

so it's a replacement to log in as your bot

slender perch
#

more just to send 1 message

#

you cant see messages back

sick birch
#

hmm i dunno, better off just dming them yourself rather than risk this

pliant gulch
#

Well, technically you log into the bot via discord.py or any other api wrapper

slate swan
#

@sick birch sorry ping but its gives error

pliant gulch
#

As you authorise it

sick birch
#

what error does it give you

slender perch
#

but how would i do anything with it?

#

like join servers, dm, etc

sick birch
#

logging into your bot is a no no

slate swan
slender perch
#

i dont even want to log in, just send one message with a discord bot

pliant gulch
sick birch
# slate swan

it's most likely indenting since the line itself looks right

slate swan
#

I can send My code here?

sick birch
#

true

pliant gulch
#

If logging into the bot was a no no you wouldn't have bots in the first place after all

sick birch
#

i mean like if you had a client, sending messages pretending to be a bot, etc

slate swan
#
import discord
from discord.ext import commands
from webserver import keep_alive
import os

client = commands.Bot(command_prefix = "+")
client.remove_command('help')

@client.event
async def on_ready():
  await client.get_channel(922899467198418974).send("online")
  await client.change_presence(activity=discord.Game(name="Meu prefixo รฉ: \"+\""), status=discord.Status.idle
  print("Estou online!")
                               
@client.command()
async def ping(ctx):
  await ctx.reply(f'`โŒ› Latรชncia do bot:` `{round(client.latency * 1000)}ms`', mention_author=False)
  
keep_alive()
  
token=os.environ.get('TOKEN')
client.run(token)```
pliant gulch
#

They seem to want a CLI though not a modified client

sick birch
#

yeah that sounds alright

#

i was just skeptical at first didn't wanna help people potentially break tos you know

sick birch
slate swan
#

Bruh i dont see this lmao

pliant gulch
slate swan
#

@sick birch ty again

sick birch
#

right

slender perch
sick birch
#

pretty sure console inputs are blocking?

#

input() i mean

#

unless there's an asynchronous version of input()

boreal ravine
#

how is it blocking lol

tawdry perch
sick birch
#

hm alright, you can use that then

pliant gulch
sick birch
#

that's what i was thinking

slender perch
#

they no add me

pliant gulch
#

ยฏ_(ใƒ„)_/ยฏ

#

they don't want help then

slender perch
#

it would only be for owners who i cant dm myself, others i would just add and dm

sick birch
#

well i mean it's your job to keep the bot secure isn't it

#

if there's a vulnerability you should take the bot offline and fix it before bringing it back online

pliant gulch
#

Also against ToS for bots to DM users without an action by the user being DMโ€™d before hand

slender perch
#

wait, fr?

sick birch
#

yeah

pliant gulch
#

Yes

sick birch
#

unsolicited dms

slender perch
#

damn never knew that

#

nvm then

outer violet
slate swan
#

ugh

#

anyone know what might cause this:

[26]+ killed python3 main.py

(I didn't press cntrl + z nor kill python3)

#
@client.event
async def on_ready():
   
    for guild in client.guilds:
        for channel in guild.channels:
            if os.path.exists("/home/bot/adx/channel"+str(guild.id)) == True:
                file = open("channel"+str(guild.id), "r")
                if str(channel.id) == file.read():
                    file.close()
                    embed = discord.Embed(title="> __Channel inactive__", color=0xFF0000)
                    embed.add_field(name="Reason for inactivity", value="Restart by developer", inline=False)
                    embed.add_field(name="Note", value="Small bug fixes || Added new categories", inline=False)
                    await channel.send(embed=embed, delete_after=60)
                    break```


also this doesn't work
torn sail
#

What doesnโ€™t work

slate swan
#

doesn

#

doesn't send the message

honest vessel
#

maybe u missed a slash

#

if os.path.exists("/home/bot/adx/channel/"+str(guild.id)) == True:

slate swan
#

nope

#

the filename is channel+id

honest vessel
#

ahok

haughty quartz
#

ayo any idea for a discord bot?

honest vessel
#

not sure but

#

if str(channel.id) == file.read():, aint file.read() gonna be a int?

#

if it just include numbers

#

u can always check what type itis by print(type(file.read()))

#

@slate swan

slate swan
#

no

honest vessel
#

or if there is any \n (newline) in that file

slate swan
#

file.read is never int

#

How can you make a emoji object out of a system emoji like ๐Ÿ”” ? Since it has no id

honest vessel
#

\๐Ÿ””

sick birch
sick birch
slate swan
#

ik but there is nowhere else to put it

sick birch
#

is it only supposed to run on startup?

slate swan
#

yes

slate swan
# honest vessel \๐Ÿ””

Well the issue is I need to pass in a emoji object for a emoji field:

interactions.Button(style=interactions.ButtonStyle.SECONDARY, label="Test", emoji='๐Ÿ””', custom_id='test_button')

which the error I receive is:

TypeError: interactions.api.models.message.Emoji() argument after ** must be a mapping, not str

Not trying to use a custom emoji, need to use system emojis

sick birch
#

then take a lower-level approach, like so:

async def main():
  bot = commands.Bot(...)
  await bot.start(TOKEN)
  # startup logic here
asyncio.run(main())

@slate swan

#

you can put all of your logic in there, it only runs once on startup

quaint epoch
#

!d discord.Member.edit

#

oh

slate swan
sick birch
#

correct

quaint epoch
#

oh

slate swan
#

hm the bot doesn't run any code

jolly shore
#

if message.author == 'FearAndPain#6427': im trying to make the bot detect if i say something

sick birch
#

you can, however, compare it to another discord.Member

#

Alternatively you can compare the id attribute of message.author to your ID

#

You may also compare the name attribute of message.author to your name without the discrim

#

there are plenty of ways to check it

slate swan
#

str(message.author)

#

works

#

cuz message.author is the users name + tag

#

ah

#

u need to use if 'FearAndPain#6427' in str(message.author)

sick birch
#

yep str() works as well except it is possible for someone else to take your name and discrim, and it will stop working if your name/discrim changes (i.e your nitro runs out)

#

better to use your ID which in theory should not change

slate swan
#

yeah ily too

sick birch
#

doing logic like that in on_ready can cause a disconnect and there's not much you can do about it

#

because iirc on_ready is when your websocket client connection recieves the GUILD_CREATE event for every guild you're in

#

send_cog_help(cog)

#

sends the help command for a specific cog

#

you can also override the send_cog_help(cog) method within your custom help subclass

#

which is probably what you want to do

velvet tinsel
#

LETS GOOOO

#

I EARNED 30 REP IN STACK OVERFLOW

upbeat otter
full flicker
#

Hey everyone! building my first discord bot and I have made some good progress. I have a good v1 working but I want the ability to add arguments in the commands and then pass those argument into the API calls I am making. I don't have a formal coding background so I struggle to follow some of the official documentation at times. Does anyone have any good links for what I am trying to do?

velvet tinsel
velvet tinsel
#

merry christmas

upbeat otter
velvet tinsel
#

bring it on

#

did you ask it?

upbeat otter
# velvet tinsel bring it on

bot = commands.bot(command_prefix=["?", "!"])

@bot.command()
async def hello(ctx):
     await ctx.reply("hey there!")

bot.run("token_smh")

Easy stuff

velvet tinsel
#

naw

#

you dont get what I mean

upbeat otter
velvet tinsel
#

I meant "is it possible to have different commands for different prefixes"

upbeat otter
#

Ohk fine

velvet tinsel
#

for example !foo says "foo" but ?foo says "bar"

velvet tinsel
#

anyways night night

upbeat otter
cinder fossil
#
bot1 = commands.Bot(command_prefix=("!"))
bot2 = commands.Bot(command_prefix=("?"))

@bot1.command()
  >code

@bot2.command()
  >code``` should work, no?
tacit horizon
#

await ctx.send(f"The ping is {client.latency * 1000}ms")

upbeat otter
cedar stream
cedar stream
tacit horizon
#

what

cedar stream
#

Round

tacit horizon
#

ok

boreal ravine
cedar stream
#

round(number, decimals) I believe

tacit horizon
#

await ctx.send(f"The ping is {round(client.latency * 1000)}ms")

cedar stream
cedar stream
tacit horizon
#

what the hell

boreal ravine
tacit horizon
#

how

upbeat otter
#

;-;

upbeat otter
cedar stream
tacit horizon
boreal ravine
slate swan
upbeat otter
tacit horizon
#

await ctx.send(f"The ping is {int(client.latency * 1000)}ms") What about this

tacit horizon
#

what ! shipit

upbeat otter
#

Smh

upbeat otter
#

Its alright

slate swan
#

๐Ÿ’”

velvet tinsel
#

carrot

upbeat otter
cedar stream
#

So, did he figure out how to use round

velvet tinsel
#

hello carrot and enslo

cedar stream
#

Hi

cinder fossil
velvet tinsel
cedar stream
#

๐Ÿ˜ญ

velvet tinsel
#

since he did int I think he screwed up round()

tacit horizon
velvet tinsel
upbeat otter
velvet tinsel
upbeat otter
#

Same thing

velvet tinsel
#

that's my boyyyy

#

or girl

#

or robot

cedar stream
cinder fossil
#

clearly the best way to solve the problem was actually to figure out first if the ping is a 3 digit, 2 digit, or 1 digit number using if statements. Next, multiply the float by 10^50 to get a long int. Once done, turn that long int to an array of single digits as chars, then create a for loop to get either first 1, 2, or 3 digits depending on what you got in the first if statement.

create a string and append those given digits to that string, and there's the ping

cedar stream
#

LMFAOOO

cedar stream
#

I wanna see the code for it

upbeat otter
cedar stream
upbeat otter
tacit horizon
boreal ravine
#

!ot

unkempt canyonBOT
cedar stream
#

I just had this crazy idea for forums bot and started on it, I planned on making dashboard and everything, then I saw that it alr exists and I dont wanna do it now

cedar stream
upbeat otter
cedar stream
#

I wanted but lost motivation

upbeat otter
#

Revive

boreal ravine
#

thats a dumb idea

cinder fossil
#

i've actually seen similar used for things like gaming servers where they have ban appeals, staff apps, etc

cedar stream
modern fiber
#

Someone good at coding bots outta here?

cedar stream
#

Ask ur question

boreal ravine
#

hiring is not allowed

upbeat otter
tawdry perch
upbeat otter
#

!rule 6

unkempt canyonBOT
#

6. Do not post unapproved advertising.

tawdry perch
#

?

upbeat otter
#

wrong rule smh

cedar stream
boreal ravine
#

is it possible to have custom responses for interaction_check

cedar stream
boreal ravine
#

a fork

cedar stream
#

Which

boreal ravine
#

every fork has interaction_check

cedar stream
#

Itโ€™ s a coroutine that returns a bool

boreal ravine
cedar stream
#

Whats ur use case

boreal ravine
#

use case? whats that

cedar stream
#

Like, what are you trying to do

#

What are you using this for

boreal ravine
boreal ravine
cedar stream
#

You can add error handler

#

@command_name.error

boreal ravine
#

it isnt a command though

boreal ravine
#

its a view

velvet tinsel
boreal ravine
#

commands cant have ephemeral messages like interactions

cedar stream
boreal ravine
#

i want it to send an ephemeral message with a custom response if someone other than the author clicked the button

cedar stream
#

Send ur response in here

#

If author == me:
Return true
Send response
Return false

boreal ravine
#

hm, how do i get which button was clicked in that

cedar stream
#

If you want to do it for specific button u can make a new class that inherits ui.Button and in callback method u check if u pressed it

#

Or nvm

boreal ravine
#

hm

cedar stream
#

You can do interaction.component to get the component

boreal ravine
#

thanks

cedar stream
#

Easier way

#

Np

slate swan
#

is 30 messages / minute a lot?

cold sonnet
#

YES

slate swan
#

hm

cedar stream
#

That is one message every 2 seconds

cedar stream
slate swan
#

nsfw bot haha

#

sending imgs every second

cedar stream
#

24/7?

slate swan
#

yes

cedar stream
#

Too much

slate swan
#

nah

tawdry perch
#

Ratelimits

cinder fossil
#

one every 2 seconmds should work with the rate limit but if they have images/gifs they'll get delayed and it'll end up being a few per second and hit rate limit

slate swan
cinder fossil
#

30/minute works in theory but it won't work for a long time in practice

slate swan
cinder fossil
#

unless you have a server with quick stable internet connection that'll never go down

cedar stream
#

Lmao bro where are u running it

pliant gulch
#

Message create endpoint is ratelimited as of speaking right now at 5/5s, if your sending 1 message every 2 seconds that is fine yea

slate swan
#

hm ok

#

nvm its actually 48 embed images / minute

#

there is no cooldown, just sends as soon as it finds a submission in reddit

pliant gulch
#

Yikes

#

Def going over the 5/5s ratelimit

cedar stream
#

U can use command groups

tacit horizon
#

what's wrong ;-;

slate swan
#

not all combined

pliant gulch
#

It's per bucket

slate swan
#

huh

tacit horizon
cedar stream
pliant gulch
tacit horizon
#

nop

pliant gulch
#

You have major parameters that form up the bucket

cedar stream
pliant gulch
#

Each bucket for sending message has a 5/5s ratelimit

tacit horizon
pliant gulch
#

You deplete the bucket then after it raises 429

#

I.e X-Ratelimit-Remaining is zero

slate swan
#

so it doesn't matter how many servers its on ?

cedar stream
tacit horizon
pliant gulch
cedar stream
pliant gulch
#

Which is hard set to 50 requests

slate swan
#

is 55 servers / 48msgs /minute much for global ratelimit

tacit horizon
pliant gulch
#

Yes you'd def get ratelimited

modern fiber
#

Anybody here has an economy bot? I want to question ya smth ab experience

cedar stream
#

Dont ask if someone can help u

modern fiber
#

It's not related to all of you

spark wigeon
#

how do i send a image through a discord webhook (ping me)

boreal ravine
unkempt canyonBOT
#

await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., wait=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects to send.
boreal ravine
#

takes a file kwarg

spark wigeon
boreal ravine
#

send it

#

!local-file

unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

slate swan
#

Been out of my city for a while just wondering has disnake added endpoints for timeouts?

boreal ravine
#

yes

#

!d disnake.Member.timeout

slate swan
#

Lets go

unkempt canyonBOT
#

await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
boreal ravine
#

!d disnake.Member.edit

unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timeout=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the memberโ€™s data.

Depending on the parameter passed, this requires different permissions listed below...
slate swan
#

Beautiful

#

Thank you

spark wigeon
slate swan
#

What's the until kwarg for?

boreal ravine
#

not sure though

spark wigeon
slate swan
# unkempt canyon

Oh you can add the time or add a date in one of the kwargs if you add one as None i guess it will disable it thats pretty cool

austere herald
#

I've upgraded to Python 3.10 and when I run my bot it throws an asyncio error and quits

#

It was working fine on <=3.9

boreal ravine
#

aiohttp issue

boreal ravine
#

or do this pip install aiohttp --upgrade

austere herald
#

aiohttp is already latest

boreal ravine
#

hm

#

no idea then

slate swan
pliant gulch
austere herald
#

Yeah

#

Should I install aiohttp from git?

pliant gulch
#

Yes, you should I'm pretty sure they have that fixed?

#

I'm not sure but better to try than to not

full flicker
#

hey guys, quick question. I am making a crypto price searching bot, so I am able to pass in the token abbreviation as an argument, but I need to pass it into the JSON search, and I am running into issues... this is what I have so far.

#

@bot.command() async def price(ctx, arg): headers = {'X-CMC_PRO_API_KEY':''} r = requests.get(f"https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol={arg}", headers=headers) json_data = json.loads(r.text) price = json_data['data'][{arg[1]}]['quote']['USD']['price'] ##volume24 = "${:,.2f}".format(json_data['data'][{arg}]['quote']['USD']['volume_24h']) await ctx.send(price)

wintry panther
#
if not guild:
  await ctx.send("Dm's Are Disabled")
  return``` how do i fix this
full flicker
#

sorry idk the best way to format code in discord lol but when I am creating the price variable it doesn't like me passing in {arg}, any ideas

wintry panther
#

say triple `

#

and annnother triple ` at the end

#

hellp

#

guild = ctx.guild if not guild: await ctx.send("Dm's Are Disabled") return

#

gives me error

full flicker
#
async def price(ctx, arg):
    headers = {'X-CMC_PRO_API_KEY':}
    r = requests.get(f"https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol={arg}", headers=headers)
    json_data = json.loads(r.text)
    price = json_data['data'][{arg}]['quote']['USD']['price']
    ##volume24 = "${:,.2f}".format(json_data['data'][{arg}]['quote']['USD']['volume_24h'])
    await ctx.send(price)```
slate swan
#

Wut does presence intent do

snow flare
#

Is there a way to get a member object if I only have the username?

wintry panther
slate swan
wintry panther
#

and member named

#

names

#

ok

slate swan
#

Oh tnx

dire folio
#

how would i make a command that resets everyone's username

spark wigeon
#

im not sure but itll look somthing like (not actually this)

#
for user in guild:
  something reset name
dire folio
#

what is the reset name bit going to be though?

wintry panther
#

how do i make a bot detect a dm and say soemthing like "dms are disabled" when it detects a dm

dire folio
wintry panther
slate swan
wintry panther
dire folio
#

tbh no clue

slate swan
#

Np

wintry panther
#

it worked with this guild = message.guild if not guild: await message.channel.send("Dm's Are Disabled") return but im using ctx now

dire folio
#

will it say that in dms or on the server

#

just change message.channel to ctx

dire folio
torn sail
wintry panther
#

oh wait

torn sail
#

Isnโ€™t presence the status of users?

wintry panther
#

thats an intent now?

torn sail
#

I think so

slate swan
dire folio
#

me brain = not working

slate swan
#

Loop over every member of the guild and change it

#

Basically loop over a Guild.members object

#

!d discord.Guild.members

unkempt canyonBOT
#

property members: List[discord.member.Member]```
A list of members that belong to this guild.
dire folio
#

i have this

async def resetnick(ctx):
    guild = ctx.guild
    member = discord.Guild.members
    for member in guild:
        await member.edit(nick=None)
torn sail
dire folio
#

what should i do?

torn sail
#

Just leave it out

dire folio
boreal ravine
torn sail
boreal ravine
#

use an instance of it

#

not the class directly

torn sail
#

Yeah I told him to remove it

dire folio
torn sail
#

You have member intents?

boreal ravine
dire folio
boreal ravine
#

i never said that

dire folio
#

is there a way i can make it so if their nick isn't changed it won't loop throught them

#

so i don't get limited

boreal ravine
#

discord.py has rate limit handling do you dont rate limit your bot, anyways add a try-except and add a pass statement to the except statement and in the try statement edit the members nick

dire folio
boreal ravine
#

yes

#

try that, it should work

dire folio
#

nope

boreal ravine
#

i have no idea then

cloud dawn
quaint epoch
#

so i have an on_raw_reaction_add event, so how do i detect what user/member reacted?

#

because idk if discord.Reaction let's you check the members that did it

torn sail
#

reaction.member?

final garnet
#

Hey guys! Iโ€™m creating a discord bot that alerts my messages to multiple servers but my issue is that I want to alert in this 1 server with multiple channels. But then instead of alerting to all the channels that I got my IDโ€™s it only alerts to one, it seems like it alerts 1 channel in every server max

heavy folio
#

my guess is the channel doesnt exist or wrong id

final garnet
heavy folio
#

waiting

silent portal
#

How can I get the member's Banner Color?

#

This one ^^

final garnet
# heavy folio waiting
@commands.has_permissions(kick_members=True)
async def alert(ctx, *, msg):#ALERT
    
    data = {
  922874978528034886 : [922875504959295579, 922874978528034888], #Banger Alerts / Server ID, Channel Name, Role ID
  884931761610563595 : [921234942405525504, 884974424468623411], #Bangers Den / Low Float
  884931761610563595 : [921890822100758528, 884974424468623411], #Bangers Den / Bangers Mid Large
  884931761610563595 : [921907840967397476, 884974424468623411], #Bangers Den / Bangers Forex
  }

    for guild_id in data.keys():
        
        guild = discord.utils.get(client.guilds, id=guild_id)
        channel = discord.utils.get(guild.channels, id=data [guild_id][0])
        role = discord.utils.get(guild.roles, id=data [guild_id][1])  
        one = Button(style=ButtonStyle.URL, label='Twitter', url="https://twitter.com/Wafaduck")
        embed=discord.Embed(title= ':moneybag: **Alert** :moneybag:', description= (msg), color=0x00FF00, timestamp=datetime.datetime.utcnow())
        embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/872295537544679484/922881014852898826/IMG_20211221_001839.jpg')
        embed.set_footer(icon_url = ctx.author.avatar_url, text='Powered by Duck Programming',)
        await channel.send(content=f"{role.mention}")                 
        await channel.send(embed=embed)
#

Here you go <

#

If you're confused, #Bangers Den (server name) / Low Float , Bangers Mid Large, Bangers Forex (These are the channel names). Same goes for #Banger Alerts ( different server)

heavy folio
unkempt canyonBOT
#

property accent_color```
Equivalent to [`User.accent_color`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.accent_color "discord.User.accent_color")
silent portal
#

tyy!!

heavy folio
#

brb i'll get on lap

final garnet
torn sail
crystal flint
#

If i mention someone in my message, how do I make a bot mention that person too? I'm trying what I can but nothing is really working.

magic ore
#

they can

silent portal
magic ore
#

it was added in 2.0

heavy folio
#

2.0

torn sail
heavy folio
#
pip install git+https://github.com/Rapptz/discord.py
#

@silent portal ^

final garnet
final garnet
dapper cobalt
unkempt canyonBOT
#

@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.

{1234: 'value'}
dapper cobalt
#

Ah, I thought you can't. Might have been made possible in newer versions.

eager trail
#
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='?')

@bot.event
async def on_message
(message):
    if message.content == "Baba boi gimme link":
      try:
        link = await message.channel.create_invite(max_age = 300)
        await message.reply(link)
      except Exception as e:
        print(f"Baba boi Err : {e}")
# MY LOG :
#   Baba boi Err : object _io.TextIOWrapper can't be used in 'await' expression

bot.run('RUN WITH MY TOKEN')
dapper cobalt
#

I'm still living in old Python, haha.

dapper cobalt
unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
dapper cobalt
#

!d discord.on_message that's what you want to use.

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.

Warning

Your botโ€™s own messages and private messages are sent through this event. This can lead cases of โ€˜recursionโ€™ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
torn sail
heavy folio
final garnet
eager trail
#

oops

heavy folio
#

is it? i dont remember using it tho

sick birch
final garnet
#

anyways, do you know how to solve that issue? @dapper cobalt

torn sail
sick birch
#

much better

heavy folio
#

oh ok

eager trail
#

my fault

dapper cobalt
eager trail
sick birch
#

yeah i'm looking

#

odd error though

eager trail
#

thx

final garnet
heavy folio
#

hmm

#

!d discord.TextChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
heavy folio
#

brb

final garnet
sick birch
#

@eager trail can you send the full traceback?

heavy folio
#

got it @eager trail

eager trail
#

okie

heavy folio
#

you cant just send a discord.Invite object

#

you must do link.url

eager trail
#

how?

heavy folio
#

wdym how