#discord-bots
1 messages · Page 109 of 1
maybe do something like that. create a private channel you can use the say command on that'll relay your messages somewhere else
nah
COnsole Gaming
You might be able to combine run in executor and stdin or some other solution, or just use aioconsole
alr
but this is for tomorrow
its 3am, thank you both alot btw yall helped alot <3
gn
night
last time i used await asyncio.to_thread(input) in one of my library examples it worked pretty well, though stuff tended to print in the way
hey guys
im looking to incorporate a tip bot in my discord
i have the official github for the chain my token is built on and they have a tipbot but im wondering if it is viable
can anybody help me take a look?
github says that can't find that repository
Same, prolly private repo
i guess they took that one down. ill have to talk to them. this one though could also be useful.... https://github.com/grasshaussoftware/avalanche-faucet is it still working?
nevermind i think its in javascript
moving to discord classic before they remove it 
does anyone know any common causes of why my aiosqlite databases keep resetting randomly? i dont wanna send the entire file of hundreds of lines of code, so many someone knows common errors? i have self.bot.db.commit() whenever i change data values, but it keeps resetting every so often
Resetting as in it drops all the tables? Or deletes all the data from the tables
im not sure what dropping table means but, i have a leveling database and it will randomly reset my levels/xp back to 0
so i guess its deleting the data?
If it's setting it to 0 then that's an UPDATE
You'll need to check your code for the places you're updating that data
Yo, I'm trying to make a select menu that has every member in the interaction.user.voice.channel, I know I can loop trough them and append them on a list and stuff, but I don't know how to access that list from the view class, can someone help me with that?
``js
issubclass() arg 1 must be a class`` bu
What does that mean im switching
slash
!d issubclass
issubclass(class, classinfo)```
Return `True` if *class* is a subclass (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) of *classinfo*. A class is considered a subclass of itself. *classinfo* may be a tuple of class objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union), in which case return `True` if *class* is a subclass of any entry in *classinfo*. In any other case, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
it takes 2 args
thats not how you use hexs
put them inside strings, # makes a comment
you can do 0xFFFFFF like this
0*
Oh so 0xBF40BF
yes
so that will fiox sintax?
yep
Arigato!
Application Command raised an exception: AttributeError: module 'cloudscraper' has no attribute 'get' I love Cloudscraper
pls help here
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
do slash commands work in discord.py?
my sister's first attempt at her own bot
import discord
import os
from discord import Intents
intents = Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@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("'snipe"):
await message.channel.send("You shoot a sniper rifle!")
client.run(os.getenv("TOKEN"))
whats the point of "client.run(os.getenv("TOKEN))"
shouldnt it be client.run('TOKEN')?
there is a separate file called env with
TOKEN=[discord bot token i aint giving it away]
idk why
huh...
for my bot i did this
Not sure where to post this but it’s for a discord bot so I’ll post here:
What is a good way to display a graph in an image? I’m looking for a simple timeline graph using the curvy lines not straight ones (sorry I know that’s a bad explanation)
I’ve looked into matplotlib but it’s just not very aesthetically pleasing. (Though maybe there is stuff I don’t know about customization with it, I don’t know much about the library)
use guild.owner
This channel is not for anything that is indirectly related to bots
Alrighty, any suggestions where I can post this question?
^
Thank you
how come discord.py won't install on my computer
i've tried
pip install discord.py
and
py -3 -m pip install -U discord.py
are you getting a pip error?
yes
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
operable program or batch file.
and the bottom one runs it but when I try to import discord in my IDE it errors as well
is your python path in your system environmental variables?
when you install python you can add the python path to PATH (that is an system environmental variable that contains various paths) have you selected that option at installation?
i did, i specified the path it was in and ran that command. same error
Code:
import discord
TOKEN = "token"
client = discord.Client()
@client.event
async def on_ready():
print("{0.user} is now online!".format(client))
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
client.run(TOKEN)```
Error:
```py
File "/home/container/bot.py", line 5, in <module>
client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: '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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
problem is it runs without errs on my pc but the bot host wont accept it
Your local version of discord.py may be outdated, make sure you're on the latest version
Yo, I'm trying to make a select menu that has every member in the interaction.user.voice.channel, I know I can loop trough them and append them on a list and stuff, but I don't know how to access that list from the view class, can someone help me with that?
idk how to check it on host
If your host gives the error, it's on a newer version
If you don't get the error locally, you're using an old version on your PC
should i check in my python folder?
Simply update the package with pip
these are the packages from host
Yes, and that's the latest - by the way, you only need discord.py 2.0.1
Your host is fine as I said.
Your local installation is outdated if you don't get the error
A host is not local
is it in site packages folder?
As I said, simply update it via pip
You don't need to look for folders, just update.
pip install discord.py
That won't update it, no
Search engines are your friend
python -m pip install -U discord.py
In that case you will get the error when running with python file.py
no
its not giving me an error
Well first of all, why on earth do you define client twice
nothing shows up
Yeah I don't think py and python is the same command, or is it on windows?
And looking at that picture you really like to have discord and discord.py
You only need discord.py
its on windows
What if you use python file.py
i removed the client that was defined 2x
Still doesn't reply my question
which?
ok
imma try
About if there is a difference when using python file.py and using py file.py
Because you seem to be double clicking the file
nope not a difference at all
Well either way you have the intents defined now
It is required for 2.0 and above
im trying on the server rn
File "/home/container/bot.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'```
import discord
TOKEN = ""
client = discord.Client()
@client.event
async def on_ready():
print("{0.user} is now online!".format(client))
client.run(TOKEN)```
Well you still need to install discord.py..
did
And you're missing the intents again
sec
Having it listed there doesn't mean the hosting provider necessarily installs it
import discord
TOKEN = "YOUR_TOKEN_GOES_HERE"
client = discord.Client()
@client.event
async def on_ready():
print("{0.user} is now online!".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 there!')
client.run(TOKEN)
im taking other code
Bad code
It's bad just because it has a command in on_message
What exactly do you need to implement, what is your knowledge level and what tutorials/articles have you read so far
Set it online where
just to be online
no commands or anything just online status
anyone what is a mistake here i am trying for first time
This code is ok for that
You are probably having issues with running it aren't you
me?
No sry
Where are you trying to run it
1st mistake is you just leaked your token and the second is you put client.run into a command function
yes
Basic python indents
This is not a correct answer to this type of question I think
then what shall i do ?
If you were a bit of more experienced you'd easily understand this
So I recommend learning python first to receive help quickly without people spending time on you to explain basic things
ye i am new trying just started learned python recently so dont know much
so u recommend me to learn python more or give it more time/
There was a nice message explaining why you shouldn't begin to learn python without previous coding experience from a discord bot
!resources or courses on google, stepik is a good platform
thanks for ur advice
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
wrong question
i just wanna run it so that my bot is online
On what machine and what environment
Nothing wrong with it
Because I've seen you attaching some screenshots of weird hosting
yes its
bot.hosting.net
Are there any instructions on how to use it and have you read & understand them
Also use a VPS if you aren't looking for free service (there are free tier VPSs too tho)
nah there aint no instructions
the hosting service worked all the time great so far
Is it paid
As you scale it won't
i mean its just a fugging 20 line code
how can it have problems
do u got a code to set a bot online
i dont rlly want anything mo
If the hosting provider is unreliable, you can have the best code it won't change a single thing
its reliable
do u have one or not?
One what?
nvm
import discord
TOKEN = ""
client = discord.Client()
client.run(TOKEN)```
Changing code won't help at all if the hosting provider doesn't install the dependencies correctly
__import__(discord).Client().run("")
``` I like your thinking.
missing intents
could use walrus mb
(d:=__import__("discord")).Client(intents=d.Intents.default()).run("")
unless discord.py supports direct intent payload
How to get user id of user who send the command?
ctx.author.id
Any syntax?
It doesn't but it does allow an empty intent object. So tbf they could've just done that.
Syntax?
You just need ctx.author.id to get the ID of the user
Looks about right.
interaction.author.id for slash tough.
yw
I couldn’t find author.id in the document
Search by just author.
yoikes
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
ah it's in commands whatever
Let me find it
There you have the author attribute that reflects a union
Pretty bad I know that from the top of my head.
When going on the class for these you see a id attribute
Which reflects ctx.author.id when put together
Ok
Or if you type hint your code correctly
You should get intellisense in your IDE/text editor
Which then should show author when you write ctx.
Also in the doc always search by object name not by object path.
E.g if I want to search author.id then I'd search for either a User or a Member object with the objects that I've got. This case being ctx aka Context.
Well the send only contains a string 
file is grey so unused.
if message.content.lower() == 'cum':
await message.channel.send('ew, you disgusting bitch')
return
if message.author.id in USER_IDS:
response = [f'shut up, {username}', 'be quiet.', 'shush.']
await message.channel.send(random.choice(response))
if message.author.id == 951975771730235465:
response = [f'shut up, {username}']
await message.channel.send(random.choice(response))```
why does it send 3 messages?
add a return in each statement, prolly all 3 are being triggered
The message contains the word you wrote, the message was sent by the user that has the ID in USER_IDS and the message was sent by the user with ID 951975771730235465
Hence all of the if statements are true and will get executed
what
Add return statements as said above or use if elif elif

Ikr
C:\Users\pellp\testing\Scripts\python.exe "C:\Users\pellp\PycharmProjects\testing\A Very Nice Discord Bot.py"
File "C:\Users\pellp\PycharmProjects\testing\A Very Nice Discord Bot.py", line 45
else message.author.id == 951975771730235465:
^^^^^^^
SyntaxError: expected ':'```
!e
a, b = True, True
if a:
print("an")
if b:
print("example")
print("new test")
if a:
print("an")
elif b:
print("example")
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | an
002 | example
003 | new test
004 | an
?
...
else can't have comparisons or anything
you do if then if you need another comparison you do elif and if you want something where if none of the previous things are true you do else on it's own
if message.content.lower() == 'cum':
await message.channel.send('ew, you disgusting bitch')
elif message.author.id in USER_IDS:
response = [f'shut up, {username}', 'be quiet.', 'shush.']
await message.channel.send(random.choice(response))
elif message.author.id == 951975771730235465:
response = [f'shut up, {username}']
await message.channel.send(random.choice(response))```
Well, see how your bot responded to "You talk utter..."
Which is not in your code sent
So there is another event, most likely another on_message, getting triggered
what's the word im looking for instead of comparison?
oh my fod
im so dumbg
All good, happens to everyone 
Check for other events in that case
import discord
from discord.ext import commands
import random
TOKEN = 'gay'
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
USER_IDS = {879004139361816596, 839883479759585330} # IDs stored in a set
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel}')
if message.author == client.user:
return
if message.channel.name == 'alabama' or message.channel.name == 'ai':
if message.content.lower() == 'hello' or message.content.lower() == 'hi':
await message.channel.send(f'hello, {username}!')
return
elif message.content.lower() == 'bye':
await message.channel.send(f'see ya, {username}!')
return
elif message.content.lower() == '!random':
response = f'this is your random number: {random.randrange(100000000000)}'
await message.channel.send(response)
return
if message.content.lower() == 'g':
await message.channel.send('ew, you disgusting g')
elif message.author.id in USER_IDS:
response = [f'shut up, {username}', 'be quiet.', 'shush.']
await message.channel.send(random.choice(response))
elif message.author.id == 951975771730235465:
response = [f'shut up, {username}']
await message.channel.send(random.choice(response))
client.run(TOKEN)
thats the code
idk whats up so
it was working befere but now it isnt
Maybe you want to remove the slurs
Can you not share code snippets that have language that doesn't comply with the server #code-of-conduct ?
And send it without
edge bot
Slurs are the same as questionable words
Which you have more than a few in the snippet
oh
"Ew you disgusting bitch" is not language that belongs here.
okay
done 👍
Thanks. Take care not to post similar things in the future
yep mb
didnt know bitch, etc was banned here
Cursing in general isn't but up to a point. When it is directed at someone it crosses a line

discord will take commission
Yea
pretty obvious
Reasons Discord is providing that button in-app
.
At last downloaded pyhton
does someone know how I can convert that with datetime ?
3000-01-01T19:00:00.000Z
so it looks like this in a webhook? https://i.gyazo.com/0c38bbfab4541820a8c44d46ee43ea5f.png
What does upgrading do?
it's probably for premium subscriptions
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Yeah but what does it actually do
Give more features ig
Hmm
I wonder if they'll accept me if I say something like I'm staff on python discord so I know a lot about discord bots?
Saddest sentence ever
Does anyone know the commission percentage?
They'll probably say you dont have enough experience
Probably

And repetitive

Discord most likely doesn't care at all about that but yeah you never know
yo
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='.', intents=intents)```
my commands stopped working, prob something is messed up w my intents
do you guys have any ideas?
I see no commands in that code
Nor any information about what command may not work
Nor what exactly doesn't work
bruh this isnt the whole code
If you use prefix commands, enable the message_content intent
Consider moving to slash commands
intents.message_content = True
We really ought to get a "doesn't working" tag
And as said, consider moving to slash commands
Yeah definitely need that
it is on
Update the library
how
"My code doesn't work"
Ok - so did your computer blow up? That would make your code not work, yes?
how do I use discord.Role.members
ty
!d discord.Role.members
property members```
Returns all the members with this role.
Returns a list[discord.Member]
so member in property members: ?
how would I define it as a variable
so members = property members ?
ok tq tq
yeh
now my bot starts, but still cant use the commands
Did you enable both in code AND the dev portal?
yepp
intents = discord.Intents.default()
intents.members = True
intents.message_content = True```
How about in the dev portal?
Are the intents actually being passed into the constructor?
uh?
Can I see the bot constructor?
intializer??
the bot = commands.Bot(...) stuff
bot = commands.Bot(command_prefix='.', intents=intents)
hmmm
You're sure you saved the file? All changes took effect? The token is of the same application whose message content intents you had enabled?
I'm not insulting your intelligence, sorry if it came out that way. It's just a lot more common than you think. Number #1 rule of troubleshooting is "check if the PC is on" for a reason 😛
I use bot.run to start my bot, I guess it is not a problem, or is it outdated?
xd, np
Shouldn't be an issue
Ahhh I think I know
Is your on message an event or a listener?
but why u need on_messsage if they works lol
Just humour me
oh, I realised I had a random on_message which was an event bruh
Yup
Thought it'd be something like that
yeh ty
@bot.listen()
async def on_message(message):
if message.content.startswith('asd'):
await message.channel.send("asd")``` Now I changed, but now this on_message listener doesn't work 😂
Doesn't work how? Is the event being triggered?
That's inside the if though
I believe you need something like
if member.status == discord.Status.offline:
# Stuff
or
if member.status == "offline":
# Stuff
uh
does the second one also work? Nice
Yeah I'd use the first one ideally
Well doesn't seem to work
Intents?
Ik I ain't got the presence intent, but I was just checking the comparing method
Since without intent, my status is returned as offline
And if you str() it
Yeah
is the Editor class from PIL or smth?
Not related to the code you've sent
Don't load it everytime then
Your CPU usage will 📈
You've never defined background, or in another scope
Load it once on startup
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
Lmao the example was made before intents were a required kwarg
so i have a generator bot for discord made in python
and if i type .gen giftcard (Example) in general it should sent something like You can not generate in this channel, go to #generator
and if i go in #generator it should work
someone knows how to do it
Against ToS, against rules - won't get help
Yeah realized that 
Intents missing
Presence intent
bro im not good at python
why
man it was example
Either way it is not allowed.
i dont want to generate nitro...
Nitro generators are, quite obvious, not allowed
man it was examplee
Your message clearly stated nitro generators
i dont want to generate nitro..
bruh
Unsure if you will get access to it for that usage
You can always try, but they may tell you to remove the status icon from the message
I'd go ahead and see what they respond
Yeah you can test on that one
yoikes
how can i get server id without ctx ?
def add_kick(member: discord.Member):
if os.path.isfile(f"servers/kick{id}.json"):
with open(f"servers/kick{id}.json", "r") as fp:
data = json.load(fp)
try:
data[f"{member}"]["kicked"] = True
except KeyError:
data[f"{member}"] = {"kicked": True}
else:
data = {f"{member}": {"kicked": True}}
with open(f"servers/kick{id}.json", 'w+') as fp:
json.dump(data, fp, sort_keys=True, indent=4)``` it for in here
What do you have at disposition
id has to be the id
Well, pretty sure you can use member.guild.id
nope didnt work i already tried that one
Or simply pass the guild ID as new parameter
might be a dumb question but how can I send multiple embeds with await interaction.channel.send()?
but like the guild id where the command gets executed
embeds=..., pass a list
Well, you call that add_kick() function somewhere
You can pass a new parameter which would be the guild ID
? do i have to manually put 100 guild ids in ther ?
????
but it worked before i just forgot what it was
def add_kick(m: discord.Member, guildID: int):
# Stuff
# In your command:
add_kick(ctx.member, ctx.guild.id)
but i want the json file to be called like the id
So?
You call the function with the guild ID as parameter
You can use it anywhere in your function
and how i make a json file from it
The same way as you do now???
this is for adding a json file
but how do i call it with the id
You have id for the server ID
Literally here....
that doesnt say that
Then use guildID in your function to reference the guild ID
ok lets try it
Then create your files or whatever you want with that parameter in your function and replace {id} with {guildID} or whatever the parameter you want
k it works
thanks
Probably want to also go for memberID instead of member
IDs are unique and can't change
ill put the discriminator behind it
Member names and discriminators can change
import discord
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == ('Complete your payment'):
await message.channel.send('checkout detected  \n@halcyon basalt')
if message.content == ('Complete Order'):
await message.channel.send('checkout detected  \n@halcyon basalt')
if message.content == ('PayPal Link'):
await message.channel.send('checkout detected  \n@halcyon basalt')
if message.content == ('Successful Checkout'):
await message.channel.send('checkout detected  \n@halcyon basalt')
if message.content == ('Complete your Order'):
await message.channel.send('checkout detected  \n@halcyon basalt')
intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
```i want to read embed to found this keyword but i don't know how
when i start my bot and i send enbed the bot not respond
thx in advance
pls help me
You're reading message content and not embed content
message.embeds[index]
will return the embed object
Then you can search in the embed description, title, etc. By using message.embeds[index]. description for example
index would be 0 if there is just a single embed sent
So
if message.embeds[0].description == "Complete your payment":
# Your stuff
Note that it will only be true if it matches exactly the text.
You may want to use
if "Complete your payment" in message.embeds[0].description:
# Stuff here
if you want to check if the description contains the text and eventually more/other text
Hopefully that helps 
import discord
import random
client = discord.Client(intents=discord.Intents.message_content())
@client.event
async def on_ready():
lst = ["Hello", "Hi","yo"]
general_channel = client.get_channel(1003479064872497244)
random_num = random.randint(0,2)
await general_channel.send((lst[random_num]))
@client.event
async def on_message(message):
if message.content == '!test':
await message.channel.send("Testing")
client.run('Token')
why won't it receive input?
Your bot will never send the Testing message for two reasons
• You are checking if the author of the message is the bot, if not it will do nothing
• You are missing the message_content intent
ohh
lemme try that
import discord
import random
client = discord.Client(intents=discord.Intents.message_content())
@client.event
async def on_ready():
lst = ["Hello", "Hi","yo"]
general_channel = client.get_channel(1003479064872497244)
random_num = random.randint(0,2)
await general_channel.send((lst[random_num]))
@client.event
async def on_message(message):
if message.content == '!test':
await message.channel.send("Testing")
client.run('Token')
it says flag_value object is not callable line 3
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
Replace intents.members with intents.message_content for your case
Not necessarily, you can use
import discord
intents = discord.Intents.default()
...
ok thanks
intents = discord.Intents.message_content()
client = discord.Client(intents)
like this?
No, look the example again
.
intents = discord.Intents.default() # Don't change
intents.members = True # Change for message_content
client = discord.Client(intents=intents)
lemme see
if ctx.channel.id != YOUR_CHANNEL_ID:
# Your code if in wrong channel
return
# Your code if in correct channel
ctx may be message if you're using it in an event (@bot.event that is most likely on_message) and not a command (@bot.command())
import discord
import random
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
lst = ["Hello", "Hi","yo"]
general_channel = client.get_channel(1003479064872497244)
random_num = random.randint(0,2)
await general_channel.send((lst[random_num]))
@client.event
async def on_message(message):
if message.content == '!test':
await message.channel.send("Testing")
client.run('Token')
still whenever i test the command it doesent work and the problem still persists
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Make sure to respect these correctly
if message.author.id in USER_IDS:
response = [f'shut up, {username}', 'be quiet.', 'shush.']
await message.channel.send(random.choice(response))
elif message.author.id == 951975771730235465:
response = [f'shut up, {username}']
await message.channel.send(random.choice(response))```
how would i change this to a dictionary?
Wording in your snippets are, again, pretty weird/offensive
But essentially a dictionary is
x = {
"key": "value"
}
So can't help you nore as you don't specify what needs to be the key and what the value. But you might figure that out by yourself
offensive?
shut up, {username}
is targeted to someone, so kind of offensive
idk im not too familiar w thme
Then no need to use them if you don't necessarily need them - otherwise we'd need more information on why you want to use dictionaries and for what exactly
Because saying
how would i change this to a dictionary?
Isn't helpful at finding what you want to achieve
@client.command(name="quadratic_equation", help="this is the Quadratic Equation")
async def quadratic_equation(ctx, a: int, b: int, c:int):
discriminant = (b**2) - (4*a*c)
solution1 = (-b+cmath.sqrt(discriminant)) / (2*a)
solution2 = (-b-cmath.sqrt(discriminant)) / (2*a)
embed = discord.Embed(title="Answer :",description=solution1, "\n" + solution2)
embed.set_footer(text="Made by Hamza.#0065")
await ctx.send(embed=embed)```
im tryna have two variables in teh discord embed
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
It still wont receive input
import discord
import random
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
lst = ["Hello", "Hi","yo"]
general_channel = client.get_channel(1003479064872497244)
random_num = random.randint(0,2)
await general_channel.send((lst[random_num]))
@client.event
async def on_message(message):
if message.content == '!test':
await message.channel.send("Testing")
client.run('Token')
F'?
You're still not using proper indentation
wheres your token?
@whole kite read.
im hiding it...
how
^
You sometimes have like 2 spaces and sometimes 4 or a tab and then use 2 spaces in-between
Be consistent
space out your code: makes it muchmore rasdable
Yeah that too, probably want to run some prettier on the code
Or just add some new lines after the imports and between the events etc. manually
i put it through a formatter it changed it quite alot but its still not receiving input whenever I say the command
hwat command
!test
thanks krypton
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
why?
You can just do
username, user_message, channel = message.author.name, message.content, message.channel.name
or
username = message.author.name
user_message = message.content
channel = message.channel.name
Being explicit would be better in terms of readability
i prefer the latter yeah
your code
!e
if len(tuples) == 1 and next(iter(tuples))[i] != 0: return (next(iter(tuples)),)
usefulHere = {t for t in tuples if t[i] != 0}
if not usefulHere: return False
for t in usefulHere:
attempt = search(tuples - {t}, i + 1)
if attempt:
return (t,) + attempt
return False
A = ((1, 0, 0), (0, 0, 1), (1, 1, 0))
res = search(set(A))
print(res)
A = ((1, 0, 0, 1), (0, 0, 1, 0), (1, 1, 0, 0), (0, 0, 0, 1))
res = search(set(A))
print(res)```py
You need the ```py I think
how to remove people from discord teams
maybe it's your code
maybe you have a terribly unoptimized command, but there is a chance someone is ddosing you
hello could someone help please with this program? i'm having issue with this right now and don't know if there are other problems 'int' object has no attribute 'shuffle'
import random
current = 0
random = 0
Fel = 0
List_lif = [
["Hur gammal är du?", "21"],
["Vilken årstid är vi på nu?", "Höst"],
["vad är korta namnet för central processor unit?", "cpu"],
["vad står GPU för?", "graphics processor unit"],
["vad står RAM för?", "random access memory"],
["vad är Microsofts operativsystem?", "windows"],
["vem är CEO:n av Microsoft?", "satya nadella"],
["Hur många MB är en GB?", "1024"],
["Till vilket företag tillhör core i9 processorer", "intel"],
["Tänker du köpa RTX 4090?", "ja"],
]
while True:
current.shuffle(List_lif)
answer1 = input(list_lif[0][0])
if answer1 == list_lif[0][1]:
print("Rätt")
score += 1
elif answer1 != List_lif:
print("Fel svar")
score += 0
Fel = 1
i = input("Vill du förtsätta?" "\na)Ja \nb) Nej")
if i == "Ja":
continue
print(answer1)
elif i == "Nej":
print("Bra jobbat")
print("Du fick" + str(score) + "Rätt")
print("Du fick" + str(Fel) + "Fel")
score = float(score / 10) * 100
print(score, "%")
if score >= 60:
print("Godkänd")
else:
print("Underkänd")
exit()
print("Du fick") + str(score + "Rätt")
print(score, "%")
if score >= 60:
print("Godkänd")
else:
print("Underkänd")
use codeblocks, and how is this related to discord bot development?
So im hosting my bot atm on heroku (I have free paid subscription) and im using SQLite3 / aiosqlite and everytime I deploy a new update all the information stored on db is lost since Heroku doesn't save it. Is there any way to fix this?
codeblocks like?
use `````` ```
so it makes this around
block around code
don't use heroku 👍
well what else could I use
that its either free or cheap and would fix this problem?
self host or ask in #965291480992321536 for host suggestions
humm I cant see that channel XD
Heroku isnt bad with HTTP interactions only
took out both my bots at once, i figure must be a loop in how im connecting to website
Hello, I have a question, can I somehow implement a check of how many people are sitting with the microphone / headphones turned off in the voice channel. And if, for a certain time, his headphones and microphone are turned off, give out a temporary role and shoot after it is blurred?
Sure, though you'd need to store the time a user went into deafen mode into memory
!d discord.on_voice_state_update see here for more info on how to do that
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
Is it a good idea to open and close a database connection at the beginning and end of a command instead of just being connected when the program starts? I'm going to make something that uses a temporary table in Mariadb which means I'm gonna have to rewrite my commands such that I open and close the connection when the command is issued instead of just being connected when the bot starts
use a single connection pool for the complete bot and open and close connections using that in the command invocations
use aiomysql for the purpose
Hello , is there any way to get the last message of a channel ?(using discord's APi)
GET request to /channels/{channel.id}/messages then you have the list of messages, you can easily find the last message sent aka index 0
Thx a lot
If you use an API wrapper like discord.py you can use
!d discord.abc.Messageable.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
There is an example shown on how to get the messages, and the last sent will also be at index 0
Thx , that's excactly what i needed , i'll give it a try once i can
Is it better to have a bot with lots of features or a bot focused on 1 feature?
Depends what that one feature is. You can focus on one concept though and have multiple features and commands around that.
The era of multipurpose should finally move away, if that's what you want to do
Hey guys, I deployed a discord bot with repl.it and uptime robot but I'm only able to get a maximum uptime of 1 hour, I've configured everything but after I close my tabs the bot lasts for 1 hour maximum and its out
after it shuts down it gives me an https error but it works after I run it half an hour later
Hey, on message event doesnt have a reply attribute?
Also can I ignore letter case somehow?
Convert to lowercase
use .lower() or .upper()
^
I miss hosting my bot on vsc even though it utilized my resources 😢
You can apply for the github student dev pack
don't host on vsc
If you are a student
thats worse
it works maximum for an hour with tabs closed
ikr-
@bot.listen("on_message")
async def on_message(message):
if 'van admin tgf' in message.content:
await message.channel.send("Nincs!")```
just use ur terminal to run the bot
@bot.listen("on_message")
async def on_message(message):
if .lower("van admin tgf?") in message.content:
await message.channel.send("Nincs!")```
like this or what?
and there is a mistake in it
message.content.lower()
@bot.listen("on_message")
async def on_message(message):
if message.content.lower("van admin tgf?") in message.content:
await message.channel.send("Nincs!")```
Like this?
and you need ctx
can sb help me?
You don't need that.
no, you need to lower the message that was sent
oop sorry I thought it was another function didn't notice on_message lol
wat
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
@bot.listen("on_message")
async def on_message(message):
if message.author.bot:
return
if "van admin tgf?" in message.content.lower():
await message.channel.send("Nincs!")
ty
i think the bot.proccess i thing is not necessary as its a listener
a member attribute is missing
It's not overwriting the event
Edited
is it possible to run other asyncio function in the same file as discord bot/client?
yep
How?
It's possible but I have no clue with that you want to do.
Run 2 commands at the same time then you run 2 async functions at the same time.
What is in the "discord bot/client" file.
ty @cloud dawn
Any knowledge user could help me on #965291480992321536 ?
Hi there , I'm just had tried create a discord bot according to freecodecamp youtube video.But have an issue that the bot only respond via dm channel and not respond normal channel. Any idea?
you need to enable Intents.message_content
should I implement to code or via developer portal application settings ?
my code is currently like that: discord.Client(intents=discord.Intents.default())
my recommendation is if you're trying to make the bot as big as possible to sign up to amazon web services for 1 year free trial
if you're trying to add to the event loop you can use client/bot.loop.create_task(your_function())
That isn't a default value anymore is it?
what do you mean, it works for both my bots
thanks , it's working now
bot.loop was never documented but they havent changed it either
asyncio.create_task(...) would also be sufficient since you're usually creating that task from the same event loop anyway
does anyoen know this
what i did wrong 2022-10-20 17:54:53 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File R\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File \Discord bot.py", line 9, in on_ready
test_channel = await client.get_channel(1032312979594682491)
TypeError: object TextChannel can't be used in 'await' expression
try without the 'await'
i did
so test_channel = client.get_channel(1032312979594682491)
still saying error
which new error
see
2022-10-20 17:56:51 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File \AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "\Discord bot.py", line 11, in on_ready
test_channel = send('Hello')
NameError: name 'send' is not defined
can you send ur whole code?
I think u mixed some things up
ok
import discord
import http
client = discord.Client(intents=discord.Intents.all())
@client.event
async def on_ready():
test_channel = client.get_channel(1032312979594682491)
test_channel = send('Hello')
client.run('')
there
test_channel.send
import discord
import http
client = discord.Client(intents=discord.Intents.all())
@client.event
async def on_ready():
test_channel = client.get_channel(1032312979594682491)
await test_channel.send('Hello')
client.run('')```
=
try this
CAN I PLS ADD YOU AS A FRIEND?
wow ik i am new
and watching youtube
and i did everything right but it was still wrong
the '=' sign is to declare a variable, not executing a function
@silent portal
help me pls
myEmbed = discord.Embed(title="Current version", description="The bot is in version 1.0"=0x00ff00)
^
IndentationError: unindent does not match any outer indentation level what did i do wrong
if i'm checking if something is an emoji through len(), emojis can't be longer than 2 right?
wdym with using len()? Len is to check the length of smth
i want something simple to figure out if a string is a single emoji
can you chek what i did wrong myEmbed = discord.Embed(title="Current version", description="The bot is in version 1.0", color=0x00ff00)
^
IndentationError: unindent does not match any outer indentation level
myEmbed = discord.Embed(title="Current version", description="The bot is in version 1.0", color=0x00ff00)
await ctx.send(embed=myEmbed)```
everything else is 9+ characters
i guess a length check would be as simple as it gets
and yeah you can measure len for emojis
still wont wrok
oop
for what use?
!e
print(len("🤦🏼♂️"))
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
5

is it a command?
should i send the whole script
yes its an embed i am making
making a gui system that isn't a pain in the ass
@slate swan try this
oh I see, haven't used len for emojis so idk if I'm honest xd
still wont work
import discord
import http
client = discord.Client(intents=discord.Intents.all())
@client.event
async def on_ready():
test_channel = client.get_channel(1032312979594682491)
await test_channel.send('Hello')
@client.event
async def on_message(message):
if message.content == 'what is the version':
test_channel = client.get_channel(1032312979594682491)
myEmbed = discord.Embed(title="Current version", description="The bot is in version 1.0", color=0x00ff00)
await ctx.send(embed=myEmbed)
myEmbed.add_field(name="Version Code:", value="v1.0.0", inline=True)
myEmbed.add_field(name="Date Released:", value="October 20th, 2022", inline=False)
myEmbed.set-footer(text="This is a sample footer")
myEmbed.set_author(name="One Piece")
await test_channel.send('The version is 1.0!')
client.run('')
what's ur error
see that
.<
u gotta change some things up
oh
lemme help
ok i need to go in some min
@dull terrace personally ive used the emoji package to check if its an emoji, they have a bunch of constants defined
@client.command()
async def version(ctx):
embed = discord.Embed(title="Current version", description="The bot is in version 1.0", color=0x00ff00)
await ctx.send(embed=embed)
@slate swan ^^
yes
try this and remove the other things u have there
now this bruh @client.command()
^
IndentationError: unindent does not match any outer indentation level
question, let's say I have a command that iterates through a list with over 100k entries or I want ti do large iterations. Wont comprehensions and for loops create small blocks as I can't run multiple loops concurrently?
they're using discord.Client, so commands wont work iirc
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
async def gui(user, partner, event=None, item=None):
end, buttons = f"{user.scavanging_run}#{user.id}#{partner.id}", []
for label, custom in config.EVENT_GUI[event]:
if len(label) < 8:
buttons.append(Button(emoji=label, custom_id=f"{custom}{end}"))
else:
if partner.nick > 15:
partner.nick = partner.nick[:12] + "..."
label = label.replace("partner", partner.nick[:15])
label = label.replace("loot", item)
buttons.append(Button(label=label, custom_id=f"{custom}{end}"))
return [ActionRow(*buttons)]
this is the code so far, should make it a lot easier to just pull labels and the start of custom ids from a dictionary
right right
soo what do i do still dizzy
first of all you should change to commands.Bot in order to use commands properly actually, also it looks like you don't really got basic python knowledge. consider learning it first, it will help you a lot
yea ik
but if i make an bot with soem code i can learn from it
watch some youtube videos, the basics are easy to learn
ik i am watching but how do i fix the bot pls help
this is the last time
getting into discord bot development really won't do that much
i really need help i have training and need to go
@slate swan
but i want this to work
your indentation is off, you will need to fix it in order to use your stuff. i wont give you a whole lesson about it now, but after every : in python, you will need to indent the next code block, unless you dont want to do anything after those statements
indentation is common python knowledge brah
^
bruh yk what i dont understand a bit sorry
its like when you write an essay and you have to indent, somewhere in your code that indentation isn't proper
but i need to go i rlley wanted it to work before i left oh well i will try tmr or today night bue guys ty fo rthe help
"common" isnt the best word to use, base/basic knowledge would be more appropriate
not always
@dull terrace btw according to this emoji package the longest emoji is 10 characters long
elaborate 🤔
typehints
seeing as i'm putting in the emojis ill just have to check i don't use a huge one
i think those are the weird combo emojis
!e
a = (
1,
2
)
@primal token :warning: Your 3.11 eval job has completed with return code 0.
[No output]
Well you're just storing it
"common" would be of many occurrence, no?
there's still a level of indentation
It doesn't really matter if you indent or not(unless required). It entirely depends on what you wish.
i think youre switching me, i said that they should have basic python knowledge (which would include identation) in order to be able to code a bot properly
dont worry its only the two people kissing emojis, which are apparently impossible to write in discord because they dont allow skin tone modifiers
👨❤️💋👨👨🏽❤️💋👨🏽👨🏻❤️💋👨🏿👨🏾❤️💋👨🏿
are you talking about those lol
dang you actually wrote em >.>
Yeah sorry, but your statement isnt fully correct
discord's builtin emoji selector cant handle it
yeah well, on phone you can simply use them. iirc the windows emojo keyboard also has them
emoji*
As recommended, it is required to know the basics(perhaps intermediate) knowledge of python to code a discord bot. Basics include everything of python.
Your point makes no sense with my context
thats like asking about an apple and getting a document about a banana
wasnt the context that they did need to learn basics (indentation mainly)
Isn't indentation included in the basics of almost all programming languages?
html: 
ok its not a programming language sorry
tbf he said almost all
i think brainfuck doesnt have intendatiom
i wouldnt say almost all of them either but sure
just out of interest, which one would be in your head rn
So, what's your point?
Either way, my point is in python indentation doesnt depend on colon placement
oh
Yes
That's it?
Do you expect something else?
¯_(ツ)_/¯
i was trying to make them aware that their indentation was off due the colon
But your context was too generally and i corrected it
nothing more nothing less, lools like we misunderstood each other
will be more specific next time, ty
👍
You probably have a string somewhere and a float and try to put them together, the library you're using doesn't like that
!e
val = '10'
x = 1.2
z = val*x
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: can't multiply sequence by non-int of type 'float'
Check that your values are actual integers or floats depending on what you need
Your percentage is a string, needs to be an integer
I suppose result_level[4] is your percentage
If that's the case just give that in percentage=...
You are passing a string
You need to pass the integer
percentage="..." # Not good
percentage=20 # Good
So now find what the percentage is
And provide that only
Well that will never work
You need to provide one single integer
You can't just remove the "" and think it will work
Since I don't know what result_level[4] and result_level[3] is, can't really help
Again, no.
Provide one single integer
Stop trying with result_level[4] and result_level[3]
If result_level[3] is the XP needed for the next level and result_level[4] the current level, then do the simple maths behind percentage
It's just the maths behind percentage
result_level[3] is 100%
result_level[4] is X%
Rule of three
Nothing related to python, that's one of the first rules you learn at school in maths class
I mean, I can send the way to calculate that but I believe you've learned that at school so not needed
Search for the rule of three on google
There's probably a picture with a table and the easy calculation behind it
dreisatz ;)
yeah
should help to imagine the table
and find the operators
eh no
!e
current = 26
next_level = 873
percentage = 100*current/next_level
print(percentage)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
2.9782359679266897
Never looked at that in maths?
quick maths
:o
You probably did
Otherwise really look a youtube video about that, it's one of the only thing in maths that I still use these days
Well that's the table
wait
the 100 stays
| % | XP |
|-----|------------|
| 100 | next_level |
| X | current |
You have all 3 just not X
So X = current * 100 / next_level
Multiply both in diagonals and divide by the remaining one, next_level
int(...) as it may return a float
Should be fine
@slate swan can u send me a fr rq
class event(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(member):
channel1 = self.bot.get_channel(767370104814960640)
await channel1.send(f"{member} has joined the server")
@commands.Cog.listener()
async def on_member_join(member):
channel2 = self.bot.get_channel(766620766237753345)
await channel2.send(f"{member} has left the server")```
why does he swear at me on self and say that there is an error, although everything is ok in other files ??
|
V
async def on_member_join(self, member):
|
V
async def on_member_join(self, member):
just highlights with an orange wavy line
Note that you have twice the same event, might want to rename the other one
thanks. I look and I don't understand what the problem is I'm completely crazy
Why you using {} in the middle
It's a function, use ()
And you are missing an int() around result level 4
Meaning int(result_level[4])
Send me that line
I'll clean it up you're using way too many ()
What type does the function threshold return
i just tried to get a channel's message with get , and can't get it to work 😭
here's my code:
so it returns an int
import requests
import json
def retrieve_messages(channelid):
headers={
'authorization': '' "
}
r=requests.get(f'https://discord.com/api/v9/channels/{channelid}')
jsonn=json.loads(r.text)
print(jsonn)
for value in jsonn:
print(value, '\n')
retrieve_messages('1032709297383145492')
author hidden on purpose
What JSON you get back?
Also use code blocks
!codeblock
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
{'message': '401: Unauthorized', 'code': 0}
Then you're not authorized to get the messages list
In that channel
int(100*int(result_level[4])/threshold(result_level[3]))
Should be fine
weird , cause i got the authozisation , how am i suppose to fix this ?
the one i got on my browser into dev mode with an alt account
ah fk , so how can i get a bot token ?
Create a new application, then switch to the "Bot" panel and create a bot
You will then see that
Which you can then get a token from
oki , thx ❤️
Then the header will be
Authorization: Bot TOKEN_HERE
when i click on add bot it says "Too many users have this username, please try another." :/ i've already created a new account but still displaying this
And in order to make a message with buttons, you just need the message id and the standard creation of buttons, as for commands ?
Change the name of the application
Too many bots with the same name so they don't allow it
To make a message with buttons you just need to send a message with a view that contains the buttons
it works ! thx
this should be done under ?
async def on_message(message):
Can I add a button to existing messages ?
If it was sent by the bot, yes - edit the message and add a view
question, let's say I have a command that iterates through a list with over 100k entries or I want ti do large iterations. Wont comprehensions and for loops create small blocks as I can't run multiple loops concurrently?
Not related to bot development, you'll get more chances in #❓|how-to-get-help or #async-and-concurrency
annnd i got an other error
import requests
import json
def retrieve_messages(channelid):
he={
'authorization': Bot 'hidden'
}
r=requests.get(f'https://discord.com/api/v9/channels/1032709297383145492/messages' ,headers=he)
jsonn=json.loads(r.text)
print(jsonn)
for value in jsonn:
print(value, '\n')
retrieve_messages('1032709297383145492')
it says invalid sintax , and if i remove the "bot" part it says Unauthorized
oohhh , ok , now i have a Missing acces error , jeez so many errors
Means the bot doesn't have the permission
Needs the VIEW_CHANNEL and READ_MESSAGE_HISTORY permission for the bot
i selected those but it gives me a number and idk what to do with it 😢
Oh that should go in the invite
in the invite ? i need to add an invite part ?
Meaning when inviting the bot to the server, you need to add that number in the URL such as
https://discord.com/oauth2/authorize?client_id=<client_id>&scope=bot+applications.commands&permissions=<permissions_number>
Then go on that page and invite the bot in the server where the channel is
oh , the bot wasn't on the server.... XD
yep
do i have to log in as the bot or can i do it directly on the app menu ?
You click go the URL that's it
Then choose the server where the channel is
And it'll be added
yeeeeeeesss it works ! thank you so much for your time and patience
looks cute tho
nice work
@slate swan check out my github, I have one https://github.com/BeroWasTaken/discord-welcome-with-image
For discordpy 2.0
pip install -U git+https://github.com/Rapptz/discord.py
it's now released on PyPi, so can be done directly (pip install discord.py)
oh didn't know that
I'd recommend using
python -m pip install discord.py
In case you have multiple Python installations
You are sure it will be installed for the installation that is used for the python command
@slate swan
it shows him error w client but we dont have client in the code
Don't know why you're opening that in the embedded Python
Use python file.py to execute your file
the file name is main.py
Then use python main.py
In your terminal or cmd
worked
finally
thought i was done with it... but the dictionnary obtained with the json shows than the message contain nothing but it does... "content" is empty
Oh yeah enable the message content intent in the developer portal in bot tab
same place where you got the token
if you scroll you see a privileged intent section, look for the "Message Content" one and enable that
should be good after that
have i use discord.py? or i would try pycord?
i've already put admin perms but content is still empty weirdly ... that's the only thing that's not displaying , everything else's displaying correctly
not the perms
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
so even with admin it can't read messages ? weird
Click on your app, then "Bot" section
Then scroll down and toggle the check under "Message Content"
I'd use discord.py
thx
It's not perms as said, it's discord limiting bots from reading content due to abuse etc.
i enabled it and even with it being enabled it's still displaying nothing :/
{'id': 'hidden', 'username': 'impérial x', 'avatar': '0d9a2658ddf9441824b512d932618e9f', 'avatar_decoration': None, 'discriminator': '7800', 'public_flags': 64}, 'attachments': [], 'embeds': [], 'mentions': [], 'mention_roles': [], 'pinned': False, 'mention_everyone': False, 'tts': False, 'timestamp': '2022-10-20T17:38:23.474000+00:00', 'edited_timestamp': None, 'flags': 0, 'components': [], 'message_reference': {'channel_id': '735188487615283232', 'guild_id': '729837326120910915'}}
Once the check is enabled should be fine
oohhh ok
Try sending a new message and checking again
oh yeah now it's working , thx
hi can i get a quick help?
@silent portal
you wanna help me?
Go on, just say
ok soo
i am doing an bot and i did this why is my bot not responding when i say "what day is it?" it should say the day is 21th but it doesnt
from cgi import test
from math import degrees
import discord
import http
client = discord.Client(intents=discord.Intents.all())
@client.event
async def on_ready():
test_channel = client.get_channel(1032312979594682491)
await test_channel.send('Hello')
@client.event
async def on_disconnect():
test_channel = client.get_channel(1032312979594682491)
await test_channel.send('Hello')
@client.event
async def on_message(message):
if message.content == "What day is it?":
test_channel = client.get_channel(1032312979594682491)
await test_channel.send("The day is the 21th")
@client.event
async def on_message(message):
if message.content == "Thank you for telling me!":
test_channel = client.get_channel(1032312979594682491)
await test_channel.send("No Problem AnyTime :)")
client.run('')
!codeblock
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
do you know what i did wrong
Yes
and why the bot is not respondig the first time but the second time
Though next time use code blocks so that it's easier to read
code block?
how do i do that
Well, that's why I used that command :)
so i just say !codeblock
!codeblock this