#discord-bots
1 messages ยท Page 697 of 1
no
wdym
If bot has prefixes ! And ? As example, would it be possible to have different commands for that ? Prefix
uhhh
afaik no
but you can have multiple prefixes
nah , but you can for sure check what prefix was used when the command was invoked
!d discord.ext.commands.Context.prefix
The prefix that was used to invoke the command.
im gonna go ahead and ask stack overflow actually
That would be useful, I can make custom decorator for that
yea
Gl, you will get hated with 99% change
0.2 % change to get help and other 0.8 is mystery
yeah, I get like -100 downvotes each time
why ๐ญ
pog
I just gained 2 rep for editing
? what was the solution?
that's not true.
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
How to solve this dumb issue
so i added this b.se command to my database file and then I think it should work
please tell us what you're trying to do and your code
Are you scraping?
Because that looks like html jargon
replace doesn't scan every html entity and convert them to characters
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?
!e
import html
print(html.unescape("โ"))
@visual island :white_check_mark: Your eval job has completed with return code 0.
โ
Tysm
oh youre web scrapping it ?
nvm you already got the answer
ah wait
U can simply do member.send BTW
How do I make my bot dm the user who invited the bot
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'```
on_member_join has attribute (guild)
so you don't need to use member.guild.id
just replace with guild
like py on_member_join(member,guild)?
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.
@client.event
async def on_guild_join(guild):
#do something```
hmm i dont think this will work
You want to dm a member?
yes
DM who?
the joining member
When someone join, you want your bot to dm him/her?
yes
!d discord.on_member_join
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.
and i want the icon of the server the member joined
are you using discord.py???
Finally!
nextcord
bruh I am telling about discord.py ._.
ok
oh ok
Jesus Christ man. 
No. on_guild_join() returns a Member object pertaining to the guild it just joined.
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
@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??
how to get the guild name in the 'on_message' function?
I want to do it using integrations
@client.event
async def on_message(msg):
guild=msg.guild```
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
avatar.url
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
])
can anyone gimme an example or reference to slicing an embed coz lyrics command be giving me 4000+ characters....
if you have a 4000 characters long string, you can chuck it into a paginator and it will do it all for you
reference is wt i'd like...please?
You can use something like textwrap.wrap() for chunking the string into a list of smaller strings
!d textwrap.wrap
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.
???? I was pulling it up for him? Did you not read anything I said?
issa lyrics command tho...
Nvm I just couldn't find bot-commands so I mentioned it to find it๐
Lost it again
#bot-commands
Your point being?
If you need a paginator you can make one yourself or see one online.
aighty
Python wrapper for discord.py pagination.
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
ya cant
i agree
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?
darn i guess i'll need a different verification system
!d discord.Webhook
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)"):
is this 2.0
What is the time period?
fuck where did it go
a day or a week, depends on the occasion
damnit
Then i recommend using a database.
anyone know where AsyncWebhookAdapter went?
oh turns out i dont even need it
It was removed, let me check my code
makes sense ig, ima have to fresh up my knowledge on that
Then use on_message.
using discord.ui.Button, how do you check which button they press with button.callback?
please ping me on respoonse, thx
can someone link me an article or doc on how to implement the timeout feature
discord.errors.ExtensionFailed: Extension 'cogs.utility' raised an error: TypeError: 'Button' object is not callable Please explain?!?!?!
well it might be nice if you showed what Button is and what you're trying to call 
Button is probably discord.ui.Button
and i think im trying to call this:
because without this it works
.
also pls ping me when respond because i have to go now ill check messages later
Which library
any
the decorator is .ui.button iirc , Button is the class
!d discord.ui.button
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
Yeah
Ghost ping, very cool
I think I did, if you take about the new timeout feature
!d discord.ui.button
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
yeah
can you give me any sort of guidance on how to use it
try:
loop.run_until_complete(start(*args, **kwargs))
except KeyboardInterrupt:
loop.run_until_complete(close())
# cancel all tasks lingering
finally:
loop.close()
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
await bot.process_commands(message)
gives error
AttributeError: 'NoneType' object has no attribute 'id'
are you sure await bot.process_commands(message) raised that error?
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'
^
how i can ban a member who is not in my server ?
can you print(message, type(message)) pls
'''''psy '''print (hello world)
<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
@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
err
!d discord.Guild.ban
@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)
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.
client and bot?
I got a warning lol
And typehint the user param to discord.User instead of discord.Member @steep estuary
how i can ban a member who is not in my server ?
why do you have
a client and a bot
idk

Doesnโt that take a snowflake tho?
I started with client and changed to bot later lol
thats prob why its erroring
shouldnt be
Works if you give it a Member or User object
Oh. Didnโt know 
Because I'm pretty sure they're also snowflake objects, i could be wrong since I don't really look at the source code 
Regardless, from my own experience, if works 
Interesting 
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
help_command=None and then you can just make a help command
ok
^ in which case None will change to your class name
there is great tutorial for subclass stuff in pinned messages tho
this gives error Exception - 'User' object has no attribute 'ban'
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)
It's an awaitable, don't forget about that 
HELP ME
my bot...
@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
yes
and member: discord.User gives error Exception - 'User' object has no attribute 'ban'
ofcu cant ban any discord.user
@steep estuary
ohh
help me pls
srry i didn't focused on it
Let's see the code
Step 1. Don't use json, use a database
no code
it is decoder
i didnt used any json file
with this namesee
the path
and i should use discord.Member or discord.User
?
discord.Member
ohk
discord.User
discord.User for non guild
^
And don't fetch the user again
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)
ohk
Is that the entire traceback?
discord.User?
yes
You clearly use json
oh wait
Yes
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
Does your json file have {}
{}
had
Although as I said, the first step, is to not use json, but a database instead
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)
can someone link me an article or doc on how to implement the timeout feature
!json
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.
It's not in any fork yet
ok thanks
It's barely been released to discord, so be patient
@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
iirc someone here said disnake has added it?
Disnake will pretty soon tho
its in disnake 2.3
In the master version, yeah
I was just asking...
yea
yet, 2.3 isn't released yet
Didn't I do it alrd?
It's just not yet possible to have since 2.3 is not released
it is , if you use disnake
not yet I think, maybe possible from source
but the 2.3 is not released yet?
and yea , the perms
is it a package i need to import?
its on master though
so it's in github but not yet in pypi
actually you need to wait for that perm to be applied on discord first , and that library has it in beta , not the pypi version
alright
can I add buttons and dropdowns
!d discord.Guild.get_member_named
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.
nice
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
await it
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()
invite = ctx.channel.create_invite()
to
invite = await ctx.channel.create_invite()
you are getting an runtimeerror : didn't await xyz error right?
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
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 
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)
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))```
Well warn is not a cog
Can I convert string into int ?
Yeahh but mine code not working
Show
Just taking simple input and want to covert
Show the code
You cannot convert โabcโ into a int. Only numbers without a decimal
Yeah can you make abc a number?
Nah I can't
Can you turn โ12โ into a int but not โabcโ
That means int function can only covert any number into int
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"))
why does my bot randomly get killed
You can format the other strings however you want
it just quits and prints killed
Do you get an error or something ?
nothing in logs
no
Are you sure it's not the problem of your hosting?
prints killed ? 
That's really kinda sus
you mean c ?
no
the keyboard interrupt
z kills
oh
how so
Just show us your console either ways. An full traceback helps.
aight gonna wait till it happens again
got it
but I do have logger and there is nothin tho
just killed? No error message, nothing else?
yes
Then where is it printing killed?
huh
is print("killed") anywhere in your code?
no
I kinda remember this error somewhere
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
Do you somewhere in your code open an file
yea
ah yes ik what the problem is now
hell yea
You got yourself a memory cry
just do yourvarname.close()
better yet, use a manager
with open (...) as ...:
....
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
You shouldn't do that, even if you do that you should do it under the finally clause
try:
...
except:
...
finally:
...
hm actually I do have file.close already on everything
and you
try:
...
except:
...
finally:
file.close()
so that cant be the problem
never be too sure because if you have an close clause inside an try block it can get skipped if above statements raises exception(s)
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
Are intents or whatever those are, required with discord.py?
Yes but the intents needed to function are default with discord.py so you wouldnโt have to add any
Oh ok thanks
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?
!intents
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.
Maybe you forgot to save the file?
its recently been using lines that are commented
wth, do you have an open exec() somewhere? 
Did you restart the bot?
bro yall cant be srs
thanks
Save the file, close the previous instance of the bot and just execute the code.

ofc I saved @lament mesa , no @lunar quail , and yes I did @final iron
hmm
also the Killed is probably bcs of
#signal(SIGPIPE,SIG_DFL)
which is also commented
cuz I was using it before
Are you self hosting or using a VPS?
V(D)S
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
Are you sure your code is getting pushed to the server properly?
yes
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.
here is my filezilla log
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||
most probably because the member is not in the bot's cache
so how do I fix it?
its fine
do you mean to print that to py console or send it to discord?
print to console
in that case try just printing str(member) + "has left the server"
I don't see how that would change anything
doesnt do anything
Time for disnake
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
Looks like repl.it to me
Oh then you are just rate limited.
ah
Are you looping any change_presence calls?
yes
and im infinetly sending messages
What would you expect..?
change_presence sends a payload to the internal wrbsocket
Therefor causing the ratelimit
As you can only send like uhh
That's your biggest issue
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
I fixed it nvm
well for users its 15s, so ig it is the same for the bots
Do you have any eval commands or exec() in your code?
Users have a websocket rate limit?
Iโd assume for presences and voice stuff or?
I am talking about updating RP
!d os.remove
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...
sigh
sadge
i 100% meant to run a command on myself
Oh you guys see that new timeout feature from discord
Supperrr nice
https://gist.github.com/an-dyy/b8c81ce7f332d64e97519b07f95e76f0 No database, persistent mutes and no tasks.loop
No database, persistent mutes and no tasks.loop
they aren't fully persistent
If the user leaves and rejoins it doesn't persist?
good to see discord is taking moderation into their own hands
Basically deprecated almost most of the existing mute commands
oh, it does
!message
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.
thamks
Can someome Help me
Mmm yea it's neat, also supports X-Audit-Log-Reason as is calling PATCH guild/guild_id/members/member_id
Meaning you can do all logging of mutes strictly in audit logs
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
!e
print("Quotes inside quotes: \"Hello, world\"")
@sick birch :white_check_mark: Your eval job has completed with return code 0.
Quotes inside quotes: "Hello, world"
Ooooo ty
Wouldn't that technically mean you basically get to log in as the bot?
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
so it's a replacement to log in as your bot
hmm i dunno, better off just dming them yourself rather than risk this
Well, technically you log into the bot via discord.py or any other api wrapper
@sick birch sorry ping but its gives error
As you authorise it
what error does it give you
logging into your bot is a no no
i dont even want to log in, just send one message with a discord bot
Anyhow this is fine, your accessing the bot through the official api, not modifying the client to allow signing in via the bot
it's most likely indenting since the line itself looks right
I can send My code here?
true
If logging into the bot was a no no you wouldn't have bots in the first place after all
would be appreciated
i mean like if you had a client, sending messages pretending to be a bot, etc
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)```
They seem to want a CLI though not a modified client
yeah that sounds alright
i was just skeptical at first didn't wanna help people potentially break tos you know
forgetting a closing ) above the print
Bruh i dont see this lmao
This is just the wrong way to go about this, if you have the bots token that is vulnerable, just upload the token to gists and be done with this
@sick birch ty again
right
wdym?
i also wanna tell the bot maker how to make a secret with replit to make the bot more secure
pretty sure console inputs are blocking?
input() i mean
unless there's an asynchronous version of input()
no they arent
how is it blocking lol
there is, but not the standard
hm alright, you can use that then
So then just contact them via your user account, why do you need to strictly DM them through the bot
that's what i was thinking
they no add me
it would only be for owners who i cant dm myself, others i would just add and dm
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
Also against ToS for bots to DM users without an action by the user being DMโd before hand
wait, fr?
yeah
Yes
unsolicited dms
Is it possible I can make my bot respond with the help command when it only gets mentioned? https://mystb.in/DifficultyInstalledAbs.python
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
What doesnโt work
maybe u missed a slash
if os.path.exists("/home/bot/adx/channel/"+str(guild.id)) == True:
ahok
ayo any idea for a discord bot?
no
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
no
or if there is any \n (newline) in that file
file.read is never int
How can you make a emoji object out of a system emoji like ๐ ? Since it has no id
\๐
no it'll still be a string
you shouldn't do this sort of logic in on_ready, you shouldn't really do anything except just printing in on_ready
ik but there is nowhere else to put it
is it only supposed to run on startup?
yes
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
Can someone help
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
I'm assuming I put asyncio.run(main()) at the end of the whole code?
correct
oh
hm the bot doesn't run any code
if message.author == 'FearAndPain#6427': im trying to make the bot detect if i say something
message.author is a discord.Member object, you can't compare that to a string
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
str(message.author)
works
cuz message.author is the users name + tag
ah
u need to use if 'FearAndPain#6427' in str(message.author)
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
yeah ily too
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
Oh my goodness, you're insane, and this is not the right channel
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?
it is actually, I asked a question related to discord bots
https://stackoverflow.com/questions/70435262/is-it-possible-to-have-different-commands-for-different-prefixes-in-discord-py if you're wondering
Ehhh, btw Hi
I have a better answer to this if you would like
bot = commands.bot(command_prefix=["?", "!"])
@bot.command()
async def hello(ctx):
await ctx.reply("hey there!")
bot.run("token_smh")
Easy stuff
....
I meant "is it possible to have different commands for different prefixes"
Ohk fine
for example !foo says "foo" but ?foo says "bar"
I'm sorry, my deepest apologies
bot1 = commands.Bot(command_prefix=("!"))
bot2 = commands.Bot(command_prefix=("?"))
@bot1.command()
>code
@bot2.command()
>code``` should work, no?
await ctx.send(f"The ping is {client.latency * 1000}ms")
Baiiii, take care
How will u run both in the same file
Round it
what
Round
ok
why? and iirc you cant have 2 loops in one file, but im certain you can bypass that
round(number, decimals) I believe
await ctx.send(f"The ping is {round(client.latency * 1000)}ms")
You have to make like 2 separate apps with same token
No use round function
Int or round it
what the hell
ยฏ\_(ใ)_/ยฏ
how
;-;
Apply brain
LMFAOOO
OK SIR
by learning basic python
ma'am*
Uhhh, whatever
await ctx.send(f"The ping is {int(client.latency * 1000)}ms") What about this
God-like
what ! 
๐
carrot

So, did he figure out how to use round
hello carrot and enslo
Hi
nah someone else showed him int
||maybe not||
๐ญ
since he did int I think he screwed up round()
brain work ? ๐
good boy
LMFAOOO
Killed it
*nailed it
Same thing
Use round and put second param as 2
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
LMFAOOO
then do it
I wanna see the code for it
Writing and reading that would be a waste of brain cells
I alr wasted 90% of mine
We all are in the same boat, dear
well i dont have
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
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
Then dont
I wont
No one forced
I wanted but lost motivation
Revive
forums in discord?? why
thats a dumb idea
i've actually seen similar used for things like gaming servers where they have ban appeals, staff apps, etc
It would be a web application like google forms but it would be integrated with discord so u wouldnt have to specify ur id and tag etc.
Yes for that
Someone good at coding bots outta here?
Ask ur question
hiring is not allowed
No
Depends
!rule 6
?
wrong rule smh
?
is it possible to have custom responses for interaction_check
What library are u using?
a fork
Which
every fork has interaction_check
Wdym by custom response?
Itโ s a coroutine that returns a bool
custom response error
You can raise ur own exception if that is what u mean
Whats ur use case
use case? whats that
add custom response errors
for my command
it isnt a command though
its a view
@my_command.error
async def error_thing(ctx error:commands.CommandError):
if isinstance(error, commands.stuff):
# code
commands cant have ephemeral messages like interactions
Interaction_check triggers on_error event if it fails with an error
^
i want it to send an ephemeral message with a custom response if someone other than the author clicked the button
Dw, it wont suit their use case
Send ur response in here
If author == me:
Return true
Send response
Return false
hm, how do i get which button was clicked in that
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
hm
You can do interaction.component to get the component
thanks
is 30 messages / minute a lot?
YES
That is one message every 2 seconds
Bro why
24/7?
yes
Too much
nah
Ratelimits
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
hm well the bots running fine
30/minute works in theory but it won't work for a long time in practice
been up 2 days, in 55 servers
unless you have a server with quick stable internet connection that'll never go down
Lmao bro where are u running it
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
hm ok
nvm its actually 48 embed images / minute
there is no cooldown, just sends as soon as it finds a submission in reddit
U can use command groups
what's wrong ;-;
its on 1 server only right?
not all combined
It's per bucket
huh
but why that is not working
Do u get error
Per ratelimit bucket
nop
You have major parameters that form up the bucket
Anything?
Each bucket for sending message has a 5/5s ratelimit
nothing, but also not working
so it doesn't matter how many servers its on ?
Have u read the docs for voice?
nop
It does matter, as there is also a global ratelimit
Do that
Which is hard set to 50 requests
is 55 servers / 48msgs /minute much for global ratelimit
nvm sleep
Yes you'd def get ratelimited
Anybody here has an economy bot? I want to question ya smth ab experience
Just ask the question
Dont ask if someone can help u
It's not related to all of you
what and why
how do i send a image through a discord webhook (ping me)
!d discord.Webhook.send
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.
Proceed.
takes a file kwarg
im not sure how, can u just do a quick example. im good at webhooks its just no file knowlegde
get the file object
send it
!local-file
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.
Been out of my city for a while just wondering has disnake added endpoints for timeouts?
Lets go
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.
!d disnake.Member.edit
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...
oh thats easy
What's the until kwarg for?
i think it needs a datetime.datetime object somewhere in the future
not sure though
Ic thanks
i didnt setup my enbed correctly, how should it look?
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
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
aiohttp issue
try updating aiohttp
or do this pip install aiohttp --upgrade
aiohttp is already latest
This error is raising because in 3.10 asyncio has deprecated the loop kwarg
Yes, you should I'm pretty sure they have that fixed?
I'm not sure but better to try than to not
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)
if not guild:
await ctx.send("Dm's Are Disabled")
return``` how do i fix this
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
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
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)```
Wut does presence intent do
Is there a way to get a member object if I only have the username?
so that the bot can track member count of server
Just that?
Oh tnx
how would i make a command that resets everyone's username
im not sure but itll look somthing like (not actually this)
for user in guild:
something reset name
what is the reset name bit going to be though?
how do i make a bot detect a dm and say soemthing like "dms are disabled" when it detects a dm
wdym, will it try to dm someone and if it can't it will say "dms are disabled"
no if someopne dms the bot
Use the Member.edit method and set the nick kwarg to None
like if someone says !cheese in dms to the bot
tbh no clue
Np
it worked with this guild = message.guild if not guild: await message.channel.send("Dm's Are Disabled") return but im using ctx now
how would i change it for every user
No thats member intents right?
oh wait
Isnโt presence the status of users?
thats an intent now?
I think so
In the loop
me brain = not working
Loop over every member of the guild and change it
Basically loop over a Guild.members object
!d discord.Guild.members
property members: List[discord.member.Member]```
A list of members that belong to this guild.
i have this
async def resetnick(ctx):
guild = ctx.guild
member = discord.Guild.members
for member in guild:
await member.edit(nick=None)
Donโt do member = discord.Guild.members
what should i do?
Just leave it out
i get TypeError: 'Guild' object is not iterable
why are you using the class
Make it for member in guild.members
Yeah I told him to remove it
i tried it and it only changed some peoples nick and not everyones
You have member intents?
rate limits exist
ik but i'm not getting rate limited
i never said that
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
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
does this look right?
async def resetnick(ctx):
guild = ctx.guild
for member in guild.members:
try:
await member.edit(nick=None)
except:
pass
nope
i have no idea then
async def resetnick(ctx):
discord.Guild.members = ctx.author
member = discord.Guild.members
for member in guild:
await member.edit(nick=None)
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
reaction.member?
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
send code and error
my guess is the channel doesnt exist or wrong id
Wait
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)
!d discord.Member.accent_color
property accent_color```
Equivalent to [`User.accent_color`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.accent_color "discord.User.accent_color")
tyy!!
idk why your indents look weird
brb i'll get on lap
Probably how I copied it dw about that ๐คฃ
U said that u want to message all channels in a server?
Keys cannot be an int.
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.
they can
'Member' object has no attribute 'accent_color'```
`print(ctx.author.accent_color)`
it was added in 2.0
2.0
You can get mentions in a message with message.mentions
Nope, Only the selected channels in the server
wdym?
!e
data = {1234: "value"}
print(data)
@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.
{1234: 'value'}
Ah, I thought you can't. Might have been made possible in newer versions.
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')
I'm still living in old Python, haha.
!d discord.on_ready takes no kwargs.
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.
!d discord.on_message that's what you want to use.
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.
Perhaps u mean on_message and not on_ready
i dont think message.reply is a thing
Yep : P, I was surprised when u told me that it shouldn't be working and my code runs ๐คฃ
oops
is it? i dont remember using it tho
on ready doesn't provide you with any arguments, you're looking for on_message
anyways, do you know how to solve that issue? @dapper cobalt
It is
much better
oh ok
my fault
Do you get any errors?
I fixed it so can u help me solve that error?
thx
Nope i do not
But like I said ^^
i'll help you in awhile
hmm
!d discord.TextChannel.create_invite
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.
brb
Alright! looking forwatd to it
@eager trail can you send the full traceback?
got it @eager trail
okie
how?
wdym how
