#discord-bots
1 messages Β· Page 488 of 1
I was trying to make a simple command and theres this error and I dont know what it means. py @bot.command() #the command async def test(ctx): await ctx.send(", ".join(ctx.guild.members)) The error ```py
Command raised an exception: TypeError: sequence item 0: expected str instance, Member found
U cant I think
with what
What code? Show us lol
whats the error
means ctx.guild.members is not a list of strings
Its a list then?
There is no more error
ctx.guild.members is not a iterable of strings. Each of them are discord.Member instances. To iterate over time you would need to iterate seperately, and append the result.
eg
members = []
for member in ctx.guild.members:
members.append(member.name)
await ctx.send(', '.join(members)
oooo thanks
Rather than defined on a discord.Message instance, that function is defined on a bot instance.
tnx
is there a discord.utils method for formatting datetime.timedelta ? like discord.utils.format_dt() ?
wouldnt this be faster?
await ctx.send(", ".join(member.name for member in ctx.guild.members))
Lol. I'm not super sure about the speed because I haven't looked much in to that but yeah, that's one way to write it π
(its probably faster iirc)
[member.name for member in ctx.guild.members]
they want it as a string, not a list
What would be something cool I could do with a discord bot?
Β―\_(γ)_/Β―
What do you use your discord bot to do? π€
stuff
Hey man. That's not allowed.
Stuff isnt allowed. Gonna need to confiscate your bot.
oh it tracks whenever someone uploads a video?
i just give it a channel id and it gets the latest
I'll do that.
gl
I wonder if someone already has twitch and youtube api connectors for python or if i'll need to make my own
google made for youtube
pls help me
.join takes a list inside it
not a string
you did list comp tho
I mean ,
",".join(member.name for member in ctx.guild.members) will result an error
.
will it?
.join takes a list
ctx.guild.members is a list...
!e
list = [ 1 , 2]
print("".join(str(number) for number in list))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
12
Hmm
my point
Ow nvm me
thanks for proving i was right
hmm wait
!e
list = [ 1 , 2]
print("".join(number for number in list))
@jade jolt :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: sequence item 0: expected str instance, int found
just making sure
Maybe check your oauth link
Help me
with
Actually I want to know how to make a command which can increase or decrease channel slowmode
@jade jolt please help
!d discord.TextChannel
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelβs hash.
str(x) Returns the channelβs name.
I can't see if it helps
Thanks
Lemme see
tysm!
ok
Wdym?
i got a answer
Glad to hear
and...
i want to check that the author of message is a bot or not
what do i need to do
how can i send a message in a specific server's specific channel instead of ctx.send()?
this doesn't work
wow you use replit?
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
any error ?
btw its preferred to put levelling_channel in the function and its await ctx.guild.get_channel(id)
oh got it
i thought it is client.get_channel
but i need a specific server
that works of discord.Client()
you can use try: except
not commands.bot()
if the channel was not found it will return error
not in my knowledge i may be wrong
i need a message to be send in a specific server in a specific channel
i gueess you are right
Wahts the error?
i read it somewhere
just a sec
ok so if some one in another server uses it it will still go in that channel
also theres no need for a ctx param if u aint gonna use it
that is why ctx.guild.get_channel
withut it python throws error
huh
you need it.
await is redundant for get_x functions
wait what..
Okay lol
can i do this
okay
no one is paid
And the project is open source so...
guild = client.get_guild(guild id)
channel = guild.get_channel(channel id)
await channel.send(message)
will this work?
Yeah
i read the docs client .get_channel will work
and what about get_guild?
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
that works
i dont wanna remove the guild variable bcoz i need it
Use that
so my code will work ig
Should work properly if the id is valid
yeah it will be valid
i need the guild variable for later so i can't delete it
i think it will not cause error
i iwill try it
thanks
Hello! Can someone tell me how can I make a bot like the Tatsu bot?
||discord.py||
What does that bot do?
Well I deleted the code before and in the new code, just subclassed View and added buttons to it... Made method which would send the embed and the view (which is self)
import discord
import os
my_secret = os.environ['TOKEN']
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
await message.channel.send('hello')
@client.event
async def on_message(message):
if message.author == client.user:
returnif message.content.startswith('!how is life'):
await message.channel.send('good')
@client.event
async def on_ready():
print(f'{client.user.name}has connected to discord')
@client.event
async def on_member_join(member):
await member.create_dm('hello')
await member.dm_channel.send(f'Hi {member.name}welcome to brooks bot test server.')
client.run(os.getenv('TOKEN'))
would there be any problems with this script?
its just a simple bot that replies and greets new members
why not use bot = commands.Bot(**kwargs)
You need to enable the members intents
!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.
@bot.event
async def on_message_join(member):
channel = bot.get_channel(890120317605928990)
embed=discord.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!") # F-Strings!
embed.set_thumbnail(url = member.avatar_url)
await channel.send(embed=embed)```
i use this bot my bot not send messages
when member join
any help?
why bot bot run properly but not send message when join
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'io' is not defined```
Help
code pls
anyone know how to fix Process finished with exit code -1073741819 (0xC0000005) in pycharm?
format = "gif"
user = user or ctx.author
if user.is_avatar_animated() != True:
format = "png"
avatar = user.avatar_url_as(format = format if format != "gif" else None)
async with aiohttp.ClientSession() as session:
async with session.get(str(avatar)) as resp:
image = await resp.read()
with io.BytesIO(image) as file:
await ctx.send(file = discord.File(file, f"Avatar.{format}")) ```
you need to import io its in stlib so you don't need to install anything
Oops
What are you trying to do?
I am trying to make a poll command
@client.command(aliases= ['vote'])
@commands.has_guild_permissions(administrator =True)
async def poll(ctx,*,message):
embed = discord.Embed(title=":loudspeaker:POLL", description=f"{message}",colour=discord.Colour.red())
msg = await ctx.send(embed=embed)
await ctx.message.delete()
await msg.add_reaction(":thumbsup:")
await msg.add_reaction(":thumbsdown:")```
here it is
'NoneType' object has no attribute 'send'
Hi everyone, I need the bot to display the username in a separate chat and to which voice chat it connects or leaves every time this happens, can you tell me where to start? I don\t understand how to track the connection / exit from the voice chat of any user
import from discord import guild
ig u not import guild thats why error
or change :thumbsup: to π
anyone here who help
on_message_join ?
!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.
i changed to member
nd it's for on_member_join
Then it's intents
i changed or i alr do intents
line 10,11 and 20
alr
It should be discord.Intents.all()
ok
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
It is basically level up bot with many features like a bank, reward system etc. On every level up it gives coins, and with that members can purchase stuff from shop.
what help bro
stop. copying. code. from. google.
Why
its run?
Are u really asking "why"?
Yeah
lol
I am a beginner and I don't know things
Copying stuff dont make u smarter it only makes u more lazy
@slate swan whats your error again?
not any error
Kk
but bot not send message
withour showing error
Code?
wait i send
Also get an error handler :)
@bot.event
async def on_member_join(member):
channel = bot.get_channel(890120317605928990)
embed=discord.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!") # F-Strings!
embed.set_thumbnail(url = member.avatar_url)
await channel.send(embed=embed)```
i not setup handler
Try only guild.name and not member.guild.name
guild isnt defined
ok
ok i define and try
Hm
member.guild is correct in this case
then whats the error I see nothing that can cause the error
there isnt one apparently
Does your bot have intents enabled?
yes
it would say, wouldnt it
Show me your application intents
The application's intents
and also enable from developer portle
alr
Are you sure?
yes 100%
Hm
Try to make an basic error handler that prints the error into the console
ok i make
on_command_error(ctx, error):
print(error)
@bot.event
async def on_command_error(ctx, error):
print(error)
ik
just making sure
lol
Done? Try to rejoin the server on an alt to see if it works if not there's gonna be an error
Did u rejoin?
give a example
Wym example?
wait
Add a print to the event to make sure the event actually works lol
i am doing
Kk
@bot.event
async def on_member_join(member):
print(member)
lol i alr done
i run bot now
Did it work
no it do not prient
Show your code in a screenshot lol
are you rejoining the server?
Bruh
You need to rerun the bot everytime @slate swan did you?
sry
bruh
bruh
oooo
if they were errors, theyd show in console. correct?
yes
theyre not in console though
Looks like defined but never used error lol
hmm ic now i try
he put print = 'member joined' o.o
I just realized
yeah
me 2
@slate swan do you know basic python
lol
Didn't u type it tho-
i even put example code
ok
@slate swan
try getting the guild id then get the channel id
like ```py
guild = bot.get_guild(1234567890)
channel guild.get_channel(1234567890)
u can call get_channel from discord.Bot
Guys how can I make a message with more then one word
type more words
^
Bruh no it will give error
how
How do I add on_message_event to my bot
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.
@meager whale i assume you mean arguments?
@bot.listen()
async def on_message(msg):
```?
yes
if you want multiple word arguments for a command do
async def example(ctx, *,arg):```
the `, *,` makes the next argument multiple words.
OK so can you give my command edited
no spoonfeed
lol
we're not
You are
not
why do you need 2
put them both in the same event?
yes?
theres no limit for how big it can be
could you delete a field in an embed? And if so, how to?
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 21, in on_member_join
embed=discord.Embed(title = f':tada:Welcome to server {member.name}:tada:',colour=discord.Colour.blue)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/embeds.py", line 115, in __init__
self.colour = colour
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/embeds.py", line 230, in colour
raise TypeError('Expected discord.Colour, int, or Embed.Empty but received %s instead.' % value.__class__.__name__)
TypeError: Expected discord.Colour, int, or Embed.Empty but received method instead.```
i got it
hi does anybody know the event for command no argument error thing?
explain
missing arguments
just use 0x0000ff for the colour
commands.MissingRequiredArgument iirc
or if you want it to be red, 0xff0000, use a color picker, copy the hex code, remove the #, add a 0x prefix
ok tenks
make that parameter a kwarg
ty all i solved problem ty @jade jolt @boreal ravine @sleek ore
ok
glad to hear that
yay
how do you send an embed with a normal text above it
How do I make my bot detect the amount of reactions on a message? Like for example the message got 2 reactions on the same emoji.
("Normal Text", embed=embed) I think
thanks
np
len(message.reactions)
@client.command()
async def send(ctx, *args):
userID = ctx.message.author.id
today = date.today()
# dd/mm/YY
d1 = today.strftime("%m/%d/%Y")
message = ""
for i in args:
message = message + str(i) + " "
embed=discord.Embed(title="Gunvir Alerts", color=0x33fe9e)
embed = discord.Embed(title="Gunvir Alerts", color=0x33FE9E)
embed.add_field(name="", value=message, inline=False)
embed.add_field(name="Date", value=str(d1), inline=False)```
how do I get this to send an embed? since I added the line with "name" and "value" it wont send
you could just do message = " ".join(args)
what would that replace?
I want this to format like this
[ ποΈ] Contract:
[β
] Entry Range:
[β] Stop Loss:
[β οΈ] Risk: 3.5/5
how would I do that?
@hasty iron
'\n'.join(args)
lmao
so the command is
/send
[ ποΈ] Contract:
[β
] Entry Range:
[β] Stop Loss:
[β οΈ] Risk: 3.5/5
how would I get it to format as sent
Uhhh, just so ctx, *, args then args should be like that
Get all as *, args
Then args.split

this font
what font
for the
[ ποΈ] Contract:
[β
] Entry Range:
[β] Stop Loss:
[β οΈ] Risk: 3.5/5
you canβt change the font
Ah, thats all g
hey guys a bot from me has reached 70 servers, wasnt it like that i could then verify the bot with a license? Or why didnt i become a message or will it only come at 100 servers?
Yea, I am also confused
test
oh i think i know what you mean
idk discord hasnt sent me a message
Ah
uh i believe you should see something in the dev page
That comes at 75
idrk
thank
oh
Also, remember to make your bot leave bot farms and small servers
Else discord won't verify it
yea
message content intents pepelaugh
π₯²
i hope no one spammed it in discord servers they made 70 times that would be sad
the biggest one almost has 1K i think
Eh, the biggest one for my bot (in which it is used) is like 150 or something lmao
what do they exactly mean by "whitelisting"?
thanks
yw
It means ur bot needs to get authorized by discord or something
You need special permission from discord
To use privileged intents
so like show my id? or something else
Well, u have to show your irl ID anyways for bot verification... It's an extra form in which u gotta tell them why u need the intent
oh i think i get it
Why cant i import from discord.ext.menus ?
bot = commands.Bot(command_prefix='!')
client = discord.Client()```together??
only have one not two.
ohk
Bot does the same as Client with a few extra's
so client will be useless here
ok
How can i do something like if i say hi thenthe bot responds to the first hi and not other that follow??
what
mybe others also respond but then the bot will end up replying to them all
how can i do this im not good at async so idk
can you explain what you want more
ok 1 sec
cuz i didnβt understand anything from what you said
I ve made a command which replies to anyone saying hello(person1) but if any one(person2) ends up responding to that person1 but bot will also reply to person2 which i dont want
i dont know much of asynchronous so i dk how todoit
ur using wait_for?
wait?
are you using it
no
i still donβt get what you mean
theres something on stack lemme see
uhh the bot shud react to the first message and not those of other replying to the first message
can i see your code
@bot.listen("on_message")
async def task_hi(message):
username_mention = message.author.mention
username = str(message.author).split('#')[0]
user_message = str(message.content).lower()
chanel = str(message.channel.name)
# print(f'{username} : {user_message} ({chanel})')
for i in range(0,len(HELLO),1):
if username == str(bot.user).split("#")[0]:
return "avoiding bot"
if HELLO[i] in user_message :
print(username_mention)
general_channel = bot.get_channel(GENERAL)
print('executed')
await general_channel.send(f'Hello {username_mention}')
return ```
ok so
HELLO= ["hello", "hi", "sup", "hello there","hey", "helo"]
not that
it might respond to the second first?
wait
dude i have no clue whatβs your issue or what you want
if i write bot: thats what the bot shud do
User: Hello
Bot: Hello @User#0000
User2: Hello@Usr#0000
now here bot !!shouldn't!! respond
now u understand....
read again srry i made a mistake
oh
srry
oh so you want to check
if the bot has been mentioned inside a message?
if so, thatβs easy
!d discord.ClientUser.mentioned_in
mentioned_in(message)```
Checks if the user is mentioned in the specified message.
if the user pinged himself?
the bot shuldnt replu to user 2
who is replying to usr 1
as user 1 is to be considered new
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
Hey a nother question i just got a dm from discord that my bot reached 75 servers or more, so then i clicked on their link and they said the bot grew to fast and they now set the limit of my bot to 250 server and told me to wait a few weeks and try again but how long does it take to calm down and what should i do and what should i dont do?
itβs because youβre checking jf one of the hello messages are inside the message
thatβs why it triggers
yes
you can just check if the whole message matches the hello message
finally
reframed : how can a pause a function for a short time like half a minute
where it stops listening
after getting executed
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatβs New in 3.10βs Removed section](https://docs.python.org/3.10/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
ok ty
@bot.listen("on_message")
async def task_hi(message):
username_mention = message.author.mention
username = str(message.author).split('#')[0]
user_message = str(message.content).lower()
channel = str(message.channel.name)
# print(f'{username} : {user_message} ({chanel})')
for i in range(0,len(HELLO),1):
if username == str(bot.user).split("#")[0]:
return "avoiding bot"
if HELLO[i] in user_message :
print(username_mention)
reply_channel = bot.get_channel(channel)
print('executed')
await message.reply_channel.send(f'Hello {username_mention}')
return```
await reply_channel.send(f'Hello {username_mention}')
AttributeError: 'NoneType' object has no attribute 'send'
if i use a variable in place of channel it works
Hey there, thanks for the tips i guess? I made pretty much all of the current code (Client, handler and websocket) in the last few days. I changed a few things here and there, would you say it's somewhat better now? For the handle_events i'll be doing more processing in the websocket.py later on, but right now it's just more of a proof of concept to check it works. I'll be doing the event handling later
they aren't helping me they are busy on their own
but nobody is helping me
π
help me
you are in the wrong channel here. So I have my doubts you'll get help here too.
Also this discord is pretty much fully driven by the community. Don't expect someone to help EVERYTIME, but almost everyone will get helped at some point
any idea @valid niche
fix keepAlive in websocket.py pls
in what way is it broken?
you dont have to use a thread
and when you dont that time.sleep and asyncio.run are uh
What do you suggest?
a simple task lol
@hasty iron '__'
I was under the assumption using a thread would make it less prone to blocking
it wouldnβt block if you use asyncio.sleep
Hey guys
and you could just await the heartbeat method
message.reply_channel is None
Can anyone tell me the code of Making a Calculator Command for my bot
well i also donβt think creating a new event loop per heartbeat is good
no i mean the user accidentally blocking HB
but i hv defined
you couldβve used something like asyncio.run_coroutine_threadsafe
ah
its not able to get channel id u mean
Also pls tell me how many plugins I shall Install Like I have installed Discord and asyncio only
I don't see message.reply_channel defined anywhere, i see reply_channel defined, but message.reply_channel is not defined
and also the function name
reply_channel = bot.get_channel(channel)
print('executed')
await message.reply_channel.send(f'Hello {username_mention}')```
its been defined
read what i just said
I don't see message.reply_channel defined anywhere, i see reply_channel defined, but message.reply_channel is not defined
oh
Pls help
Unless you know a better way to avoid the user blocking HB
we don't spoonfeed
hey
well yeah ok i get it now
i want to get the username of the author of the message
seeing those two together triggered my brain for some reason
still error
i mean i'm sure there's a better way than using asyncio.run inside a thread, but can't think of it atm
why not send over the error and your code now?
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\ArcArp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\ArcArp\Desktop\PYTHON\Python Discord Bot\main.py", line 44, in task_hi
await reply_channel.send(f'Hello {username_mention}')
AttributeError: 'NoneType' object has no attribute 'send'
discord-tsting
@bot.listen("on_message")
async def task_hi(message):
username_mention = message.author.mention
username = str(message.author).split('#')[0]
user_message = str(message.content).lower()
channel = str(message.channel.name)
# print(f'{username} : {user_message} ({chanel})')
for i in range(0,len(HELLO),1):
if username == str(bot.user).split("#")[0]:
return "avoiding bot"
if HELLO[i] in user_message :
print(username_mention)
reply_channel = bot.get_channel(channel)
print('executed')
await reply_channel.send(f'Hello {username_mention}')
return ```
or i see, for some reason you're doing channel = str(message.channel.name), and then doing get_channel(channel). Why this weird back and forth, also get_channel takes an ID not a name
just get message.channelth en
instead of this super weird back and forth
understandable haha. I assume there might be a better way so i don't have to use both asyncio and threading inside each other, but HB is also called once outside the thread when it's starting
yeah i saw that
also also send HB calls send_json which is also async and used for almost every request (it's a built in of aiohttp)
await bot.get_channel(channel_id).send(f'Hello {username_mention}')
something like this
just message.channel.send
you are overthinking and making your code overcomplex
here channel is the id ri8
is_avatar_animated is a method not an attribute
that wouldnβt error, it would just return a function
massive difference and the issue in your code
oh i see
user is a disnake.Member
and i have no idea how or what
idk disnake
i assumed you were using discord.py since most are
by not coding on your phone
I don't have a pc
is_avatar_animated is a method of discord.Member, not whatever youβre using
i'm very certain that this issue is purely because you're on phone and your phone uses some alternative character or adds some invisible character that python cannot read
why do you use brackets
also Divy this is my personal preference but please use 4 spaces for tabs lol
all those things too
member = ctx.message.author
await member.avatar_url.save("newmember.png")
img = Image.open("newmember.png")
height,width = img.size
lum_img = Image.new('L', [height,width] , 0)
image = Image.open("images/template.png")
draw = ImageDraw.Draw(lum_img)
draw.pieslice([(0,0), (height,width)], 0, 360,
fill = 255, outline = "white")
img_arr =np.array(img)
lum_img_arr =np.array(lum_img)
final_img_arr = np.dstack((img_arr,lum_img_arr))
finalimage = (Image.fromarray(final_img_arr))
finalimage.save("circle.png")
ne = Image.open("circle.png")
data = BytesIO(await ne.read())
pfp = Image.open(data)
pfp2 = pfp.resize((40, 40))
image.paste(pfp2, (150, 13))
image.save("newimg.png")
await ctx.send(file=discord.File("newimg.png"))
os.remove("newimg.png")
This gives me an error: Command raised an exception error: AttributeError: read
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.

made by @vocal plover (amazing person for helping the community so much)
πΉ
he said How do I set Images from my directory? (embeds)
You should stay consistent whether or not it's a proof of concept, if you do it will be easier to make the library in the end. Such as having a random camelcase function then having a snakecase right under, makes no sense.
ah i have some variable naming issues?
yo why is my bot ofline
i'll check it out, and convert it all to snakecase
because it's not online?
It's in the websockets, the keep alive method
but hpw can i fix it lol
thanks i'll fix it now
how can i fix it
Overall id just say try to make the code readable, right now the imports are a mess and the code itself could be written cleaner imo
lol
Makes it sort of hard to read at first
make it online
how???
who knows
what do you want us to say
i added to my server buts its ofline
in the memebers lisr
well is your bot code running?
i belivie
isn't sure enough. I want you to be 100% about your case
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
i've already pushed some readability changes, just changed that camelCase to snake_case and removed some unused imports
thanks for the tips
he didn't say anything about the situation
and he just said that it's against ToS
π€¦ββοΈ
why does the code say import discord could not be reoluved
π€¦ββοΈ
install discord.py
anyways we cant help you
ERROR: unknown command "inatall" - maybe you meant "install"
you said your bot is a nuking one
when
dont act dumb
About 2 minutes ago
a tiny bit
async def check_prefix():
fetch_arg = "prefix"
db_func = discord.utils.get(bot.get_all_channels(), name=fetch_arg)
channel_id = db_func.id
db_user = bot.get_channel(channel_id)
msg_info = discord.utils.get(await db_user.history(limit=100).flatten())
msg = msg_info.content
msg_id = msg_info.id
msg_fetch = await db_user.fetch_message(msg_id)
return msg
asdf = await check_prefix()
Getting an error here - "invalid syntax". Can't figure out what to fix. Can anyone help?
How do I send files to discord if I'm on replit?
async functions can only be called inside another async function
or you could use loop.create_task or loop.run_until_complete
create_task schedules the function to run in the background
file=discord.File("color.png")?
run_until_complete waits for it to finish
Alright, thanks!
Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.image.url: Scheme "<discord.file.file object at 0x7f56e42c4a40>" is not supported. Scheme must be one of ('http', 'https').
``` ```py
f = discord.File("color.png")
embed=discord.Embed().set_image(url=f)
await ctx.send(embed=embed)
``` lol
you cant use file in discord embed image i think 
!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.
hmm
works?
yes and no

lol
one last way..
send the image to a channel, then copy the image url, then pass it

it's written there above tho
.
the result ^^
the problem is only with getting the path on replit
I think
hello guys i have a small question
i want to validate the type of channel that user sent a message
how can i do this ?
because message.channel has not attribute like type
yeah maybe
.
f = discord.File("color.png")
embed=discord.Embed().set_image(url=f)
await ctx.send(embed=embed)
f = discord.File("color.png", filename="image.png")
embed=discord.Embed().set_image(url="attachment://image.png")
await ctx.send(file=f, embed=embed)
kinda spoonfeeding
you can check the type of it
by using isinstance
message.channel , returns discord.abc.Messageable
but abc.Messegable has no attribute to find type
Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'attachment://color.png'
The code I used after asking for help: ```py
f = discord.File("attachment://color.png", filename="color.png")
embed=discord.Embed().set_image(url="attachment://color.png")
await ctx.send(file=f, embed=embed)
thanks it worked
the discord.File is wrong
?
discord.File(filepath, filename)
Thats a kwarg?
how do i make my bot to slide to my target dm?
example: .send @left apex this is message
and then the bot will send dm to @vestal hatch
How do i mention a role ?
!d discord.Role.mention
property mention: str```
Returns a string that allows you to mention a role.
Dont ping random ppl kthx
!d discord.User.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
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. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with 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. **Specifying both parameters will lead to an exception**.
I mean like discord.File("color.png", filename=...)
sorry
hmm
how do i get the mentioned id/data thing to run that?
you use a discord.User/Member object argument in your command
okay!
async def command(ctx , user : discord.User):
await user.send(...)```
hm it works @visual island thanks

π¦
AttributeError: module 'discord.ext.commands.bot' has no attribute 'event' help pls
the error is pretty clear
@tasks.loop(seconds = 30)
async def counter(self):
for key in self.serverstats.keys():
guild = self.bot.get_guild(int(key))
try:
server_stats = self.serverstats[str(guild.id)]["statschannels"]
except KeyError:
server_stats = {}
category = discord.utils.get(guild.categories, name="STATS")
botcount = 0
membercount = 0
members = guild.members
textchannelscount = len(guild.text_channels)
voicechannelscount = len(guild.voice_channels)
for member in members:
if member.bot == True:
botcount += 1
else:
membercount += 1
users_text = f"Users: {membercount}"
bots_text = f"Bots: {botcount}"
channels_text = f"Text Channels: {textchannelscount}"
channels_voice = f"Voice Channels: {voicechannelscount}"
tier = f"Premium Tier: Level {guild.premium_tier}"
uc = guild.get_channel(server_stats['member_count'])
bc = guild.get_channel(server_stats['bot_count'])
tc = guild.get_channel(server_stats['text_count'])
vc = guild.get_channel(server_stats['voice_count'])
pt = guild.get_channel(server_stats['tier'])
if uc.name != users_text:
print("1")
await asyncio.sleep(1)
await uc.edit(name=users_text, category=category)```
error:` if uc.name != users_text:
AttributeError: 'NoneType' object has no attribute 'name'`
but i have the id here
how can a bot detect whether it is able to send mesages in a channel, or when a channel unlocks?
where are you starting the loop
@commands.Cog.listener() async def on_ready(self): sChannel = self.bot.get_channel(self.botInfo['startupChannel']) await sChannel.send('serverstats cog has been loaded successfully.') self.counter.start()
π³
i dont
anyone able to do this?
i never tried anything like it
oh since you are doing it inside the on_ready cache should be filled ok
are you sure the channel is in the guild you want
AttributeError: module 'discord.ext.commands.bot' has no attribute 'event'
how to fix ?
@bot.event
async def on_ready():
await client.change_presence(activity = discord.Streaming(name = "β", url = "https://twitch.tv/gucci"))
commands.Bot
Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.
Instead set the activity and status kwargs in the constructor of these Classes.
bot = commands.Bot(command_prefix="!", activity=..., status=...)
As noted in the docs, on_ready is also triggered multiple times, not just once.
Basically: don't π do π shit π in π on_ready.
yes
https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.permissions_for
and you can use this event to check if it unlocks ;
https://discordpy.readthedocs.io/en/latest/api.html#discord.on_guild_channel_update
mine is in on ready because it needs the bot variable and you cant access a variable before writing it
ok thanks
wELL I WANNA DISPLAY THE AMOUNT OF GUILDS AND MEMBERS AND IT NEEDS BOT.GUILDS
Use a task then
hm
How do i import discord.ext.menus ?
did you install it?
from discord.ext import menus
if not installed then install it first
I tried that it said unknown locationβ¦
^
How do i install it
No documentation found for the requested symbol.
File "nuke.py", line 15, in <module>
@Bot.event
TypeError: event() missing 1 required positional argument: 'coro'```
AAAAAAAAAAAA help plsss
yes ?
No documentation found for the requested symbol.
what are you trying to do?
and show code
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
π€¨π€¨ yeah
no help about these
take shower
how do i use this? discord.on_guild_channel_update on the docs it just says before and after
parameters
Got it,thanks!
just channel objects basically (are what it gives you)
wdym lmao
Why would a nuke command be against this servers tos?
async def event(before, after):
ratelimiting, counts as raiding, several other more reasons
Aight ig
And probably api abuse
how can i move a specified member to a specified voice channel
How do I make bot clear for users?
-clear user amount?
Dont know what to type on the user thing
To make it clear
Are you trying to purge a specific users messages?
How do I set the color of an embed to a variable (hexcode)? Like e.g (color = f"0x{hexcode}") will this work?
needs to be an int
and yes that would work
How do I make my βpurgeβ command clear for specific users?
βpurgeβ user amount
What do I type?
i got this error tho Command raised an exception: TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
16777215
look its valid
yeah but the variable is only FFFFF
what
how do you make a purge command purge for specific users?
!e
var = FFFFFF
print(f"0x{var}")
!purge help
im trying to make it like this @hasty iron
Add a check
am just trying to figure out how to make my purge command clear for specific users
you know how?
yes, add a check
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelβs hash.
str(x) Returns the channelβs name.
!e
var = 'FFFFF'
print(int(f'0x{var}', 16))
oops wrong thing
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
1048575
hmmm ok
how do I move a specified member to a specified channel
!d discord.Member.move_to
await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Moves a member to a new voice channel (they must be connected first).
You must have the [`move_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.move_members "discord.Permissions.move_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").
Changed in version 1.1: Can now pass `None` to kick a member from voice.
await member.move_to(channel) whats so hard lol
bruh
my eyes
member is None
intents?
uh oh. py Command raised an exception: ValueError: invalid literal for int() with base 10: '0x1D7371' The code I used ```py
embed=discord.Embed(title='Color Machine', color=int(f"0x{hexcode}", 16))
it shouldn't be a string
pass in base as a kwarg
wait
why is it saying none
I'm dumb again
i dont get it
!d discord.ext.commands.ColourConverter
class discord.ext.commands.ColourConverter(*args, **kwargs)```
Converts to a [`Colour`](https://discordpy.readthedocs.io/en/master/api.html#discord.Colour "discord.Colour").
Changed in version 1.5: Add an alias named ColorConverter
The following formats are accepted...
hm
BTW @slate swan, I edited all the code and the paginator works again!
nice man
the move_to doesnt work
what the hell
discord.Guild.get_member(314727938492727296).move_to(839853272991006720)
why no work
await bot.change_presence(activity = discord.Streaming(name = "β", url = "https://twitch.tv/gucci"))
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\client.py", line 1062, in change_presence
await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'
pls help ?
you're trying to change the presence before the bot logged in
oh ok
use bot.wait_until_ready at the top of your function
!d discord.Client.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the clientβs internal cache is all ready.
read
and its a method of Bot/Client
user1 = discord.Guild.get_member(314727938492727296)
TypeError: get_member() missing 1 required positional argument: 'user_id'
how does this make any sense
it has user id
can u get me the correct code pls ?
@tasks.loop(seconds=4) async def mytask(): await bot.change_presence(activity = discord.Streaming(name = "β", url = "https://twitch.tv/gucci")) await wait_until_ready() mytask.start()
no
i dont spoonfeed
and i said the top of your function
and again, its a method of Bot/Client
you need an instance of Guild not the class itself
and 4 seconds is way too fast
change it to 60-40 to be safe
how do i get the instance of guild
ooops
you can get it through, Bot.get_guild, Message.guild, Context.guild, etc
that's an api call
WHY THE HELL IS IT SO COMPLICATED
it's not
it is
you're making it complicated for yourself
that points to lack of knowledge
3 hours for something that can be done in a minute
is a bit too much
you should stop making fun of me
i am not
its not about the python
it is
i know python
do you
the discord lib is stupid
you clearly dont know the difference between an instance and a class
dont blame the lib
dont blame it for your own incompetence
you should learn more python and that's it
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
that can help
take shower
i did yesterday
u r unemployed
yes ofc i am 14
not really

i genuinely thought you were 17
^
IndentationError: unexpected indent``` someone can help me ? (@hasty iron is gay)
fix your indents
sameee
lmao
actually zero in python in general
indeed
@slate swan why would anyone want to help you when you just insulted the last person who tried...
its fine
yeah.
i dont mind it
still not a nice thing to say
Also what actually is a nuke bot

something that breaks the TOS
oh just a blanket term for any TOS rulebreak?
whats a blanket term
bro-
true, discord should become a shower
I see you getting stereotyped lmao
this guy is so obsessed with other's shower
blanket term is like something that refers to anything "underneath the blanket", so like wildlife is a blanket term for uh insects, mammals and stuff
oh
well
oh your name is blanket, i completely forgot lol
not anymore, there's a blanket
lmao
hahaha that looks premade
chill
12 y/o π gf
wat
hes under 13 fs
why me
not u
probably didnt mean to?
in Member.add_roles
- atomic (bool) β Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
is this helpful?
Is there a parameter to get a certains command's information (aliases, help, desc)? Like if I do !help <command> it'll show all the command info
Should the param be command: ctx.command? or something else
commands.HelpCommand subclass?
uh no
then you can have the param as a string and use Bot.get_command
hmmm ok
that returns Command | None
wow it worked wtf thanks
@bot.listen("on_message") i hv a func
any way to make it stop listening for some time
no
hmm
i cud make a loop or somethin
@client.command()
async def ban(ctx, member : discord.Member, *, reason="No reason provided"):
await member.kick(reason=reason)
doesnt ban
it kicks
yes read what it does
i mean
lol
kick
Ban is a built in function it messes up the name
Change the name to _ban or something
@hasty iron :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'ban' is not defined
Discord.py has a ban function
Bruh
what?
It's a ban method
Of the member object
Member.ban
that doesn't shadow anything
discord.Member.ban
