#discord-bots
1 messages · Page 1010 of 1
yes exactly! but you would also need member Intents, in case you don't know what is it, use !intents command here
!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.
can anyone help me make a command to find people by putting their name? For example: .find (name) and it finds all people with that name or similar name
lol
we can't spoonfeed here but I can give you an idea on how to do it
yes, typehinting an argument to discord.User does the same
Define "find people"
not "similar" but same name works
!pip fuzzywuzzy iterate thru bot.users and use this, to compare similar names
yes
Sorry for my bad English. I'm Portuguese and I'm not fluent in English.
I'll give you a context for you to understand what I want to do:
Today there was a raid on a server that I am an administrator and I wanted to make a command that would banish all members who had a specific name.
For example: antiraid (name). And all members who had the name (name), would be banned.
What are you looking to rewrite?
My whole main file, I tried to do as told but I kept running into problems, so I just reverted everything
I've been thinking of ways to do this and the best way I found was to make the bot create a list of all the people with that specific name
Could be time consuming, but loop through all members and ban ones with "some string" in name
There are parts that are the same from 1.7.3 from 2.0, so changing everything in your main file isn't sensible
Well, the parts that need to be changed
also, you only really need to migrate if you're going from text commands to slash commands
The whole async/await stuff
Is that what you're doing?
No, I'm trying to make it so I can get my cogs to load
Cogs should be same from 1.7.3 to 2.0
Best would be to just tempban all users who recently joined.
Not the mail file
if __name__ == '__main__':
for file in os.listdir(cwd + '/cogs'):
if file.endswith('.py') and not file.startswith('_'):
bot.load_extension(f'cogs.{file[:-3]}')
this part to be exact
Discord has a native prune feature for it too
Oh I see, yeah that was made async/await
I know I need to put it in a class with some other stuff, but that's the part that I can't figure out correctly
And I've been trying for over 2 hours or something now
and I still can't figure it out
Is there any way (using discord.py) to check if someone has connected their steam account and fetch their friend code?
class MyBotSubclass(commands.Bot):
...
async def setup_hook():
await load_extension(...)
# setup stuff here
Finding if they have steam account linked, possible. Getting friend code, not really
This is what I was trying
What information can I fetch about their steam profile using discord.py
But this is what I can't figure out because I have alot more code in my main file that needs to be done
None
And what's the problem with it?
Bots don't have access to that.
I can't get it to work and I don't know if I do it correctly
Doubtful, but this is discord.py not steam.py
I thought there was a Profile class?
For profile information
I guess alternatively I can prompt the user to insert their friend code in Discord in some sort of command
Deprecated from 1.7 it seems
Yeah because it requires a self bot.
That's your best bet
So I have no idea
What do you mean "you can't get it to work"? Do you get any errors? Do your cog commands work?
Cogs won't work, and I don't exactly know what to put in the class
here i'll send my main file
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Why are you manually doing the websocket stuff
The websocket stuff is for the mobile icon status
Since he is trying to manipulate the socket into thinking he is using a mobile.
i have no clue if this is possible in python in general, but how would one add to an int without making a new variable? ```py
a = int(0)
@bot.event
async def on_guild_channel_delete(ct):
a + int(5)
print(a)
Which is against ToS i might add.
Not sure how well subclassing is going to work with a manual websocket connection
Is it?
Yes
You have to subclass commands.Bot, not DiscordWebSocket
I know, but where would I leave the rest of the code?
What do you mean where would you leave it?
class MyBotSubclass(commands.Bot):
...
async def setup_hook():
await load_extension(...)
# setup stuff here
bot = MyBotSubclass
bot.run(bot.config_token)
Because this is what I would do, right?
could someone answer please?
!botvar
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!
Yes
what?
You don't have to cast an int to an int.
!e ```py
a = 34
a += 35
print(a)
@supple thorn :white_check_mark: Your eval job has completed with return code 0.
69
like this?
Python is a dynamically typed language.
no, the variable has to be outside the event :/
its not really that long and complex to read and understand.
oh i didnt see that lol
then just put it outside
doesnt work like that but ill just do the thing and see if it works lmfao
That takes the place of your main bot instance
you are def doing something wrong then
!e ```py
class Bot():
...
bot = Bot()
bot.number = 1
def a():
bot.number+=2
a()
print(bot.number)
#clearly works
@slate swan :white_check_mark: Your eval job has completed with return code 0.
3
thanks
main file:
import json # for json
import logging # for logging
from pathlib import Path # for paths
import discord # for discord
import sqlite3
from utils.data import Bot
cwd = Path(__file__).parents[0]
cwd = str(cwd)
print(f'{cwd}\n-----')
print(discord.__version__)
async def getprefix(bot, ctx):
db = sqlite3.connect('cupid.db')
cursor = db.cursor()
cursor.execute('SELECT prefix FROM prefixes WHERE guild_id = ?', (ctx.guild.id,))
data = cursor.fetchone()
if data:
prefix = str(data[0])
if not data:
prefix = ','
db.commit()
cursor.close()
db.close()
return prefix
bot = Bot(
intents=discord.Intents.all(),
command_prefix=getprefix,
case_insensitive=True,
owner_id=742623359409586227,
activity=discord.Game(name=",help")
)
config_file = json.load(open(cwd + '/config/config.json'))
bot.config_token = config_file['token']
logging.basicConfig(level=logging.INFO)
bot.version = 'v0.1.3'
bot.run(bot.config_token, reconnect=True)
utils.data file:
import os
from discord.ext.commands import AutoShardedBot
from pathlib import Path
cwd = Path(__file__).parents[0]
cwd = str(cwd)
class Bot(AutoShardedBot):
def __init__(self, *args, prefix=None, **kwargs):
super().__init__(*args, **kwargs)
self.prefix = prefix
async def setup_hook(self):
if __name__ == '__main__':
for file in os.listdir(cwd + '/cogs'):
if file.endswith('.py') and not file.startswith('_'):
await self.load_extension(f'cogs.{file[:-3]}')
@sick birch tried to do what I could figure out, but it's still not loading cogs
hmmm
This is all that i'm getting https://tokyotokyotokyotokyo.tokyo/
class woke(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(f"{self.__class__.__name__} cog has been loaded\n-----")
This is what it should print every time a cog is loaded
You're making multiple websocket connections to the gateway
get rid of your manual connection
What manual connection?
I deleted the websocket stuff
class MyDiscordWebSocket(DiscordWebSocket):
async def send_as_json(self, data):
if data.get('op') == self.IDENTIFY:
if data.get('d', {}).get('properties', {}).get('$browser') is not None:
data['d']['properties']['$browser'] = 'Discord Android'
data['d']['properties']['$device'] = 'Discord Android'
await super().send_as_json(data)
DiscordWebSocket.from_client = MyDiscordWebSocket.from_client
``` this stuff?
can you post an updated main file
.
that's this
Those are the 2 most recent updated files
ok
INFO:discord.client:logging in using static token
Traceback (most recent call last):
File "C:\Users\ego\Documents\Development\Discord\murder\cupid.py", line 46, in <module>
bot.run(bot.config_token, reconnect=True)
File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 711, in run
asyncio.run(runner())
File "C:\Users\ego\anaconda3\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\ego\anaconda3\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 708, in runner
await self.start(*args, **kwargs)
File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 681, in start
await self.login(token)
File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 544, in login
await self.setup_hook()
File "C:\Users\ego\Documents\Development\Discord\murder\utils\data.py", line 15, in setup_hook
for file in os.listdir(cwd + '/cogs'):
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\ego\\Documents\\Development\\Discord\\murder\\utils/cogs'
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001BFF91525E0>
Traceback (most recent call last):
File "C:\Users\ego\anaconda3\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\ego\anaconda3\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\ego\anaconda3\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\ego\anaconda3\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\ego\\Documents\\Development\\Discord\\murder\\utils/cogs'
Huh
from utils.data import Bot I have this imported to make sure I get the bot class from the data file just so it can work
Right, but this is a pathing issue
I believe it should be
for file in os.listdir(cwd + '\\cogs'):
for file in os.listdir(cwd + '/cogs'): this part seems to be the issue
Nope, also doesn't work
error?
wait, i think i fixed it
ok yeah i fixed it
thank you guys for your help
especially you @sick birch
it was my pleasure!
😄
I'm taking a look at pycord. I downloaded the package but I think the library names are conflicting. I have discord.py which is referenced by import discord and I also have pycord which is import discord. How can I change the name of the package?
what do you recommend
Uninstall one of the libraries or make a locked environment
uninstall discord.py or use a venv
I'll uninstall it as I think I will be moving to pycord
alright
Ight
but i still recommend u to use venv... for all your project.. but still, your choice
:")
It keeps everything more organized
yep
and u can work with other ppl on their repo without your lib or versions affecting eachother
And if you set it up right you won't fill up your c drive with libraries
Nice
:>
Kinda weird but after I uninstalled discord.py I now don't have any packages named discord when importing. When I run pip list however I see that py-cord is still there and discord.py is gone
hmm r u using vsc?
yee
reload your vsc window
I have several times
owo
I want to mention I did run pip uninstall discord the first time
u were suppose to run pip uninstall discord.py
I did that the second time
ok
I'm just mentioning incase it matters
and it should work fine to import py-cord..
i don't see any problem with it
No spoonfeeding.
I can't import py-cord it's invalid syntax
and it's not registered under an alternative like pycord
that was 8 months ago...
and all the videos have it registered as import discord
LOL
client = discord.Client()
ben = "ben"
ben_response1 = 'yes'
ben_response2 = 'no'
ben_response3 = 'hohoho'
ben_response4 = 'blehh'
ben_responseULTIMATE = ben_response1, ben_response2, ben_response3, ben_response4
@bot.listen()
async def on_message(message: discord.Message):
if message.author.bot: return
for i in ben:
if message.channel.category.id == 937556857822773281:
return
if i in message.content:
return await message.channel.send(ben_responseULTIMATE)
bot.run(TOKEN)```
so recently talking ben was being shut down, so my friends wanted to make a scuff one, this one is basic and just responds to anything and doesnt respond with the right thing either, any tips?
You need to add more if statements & in the right place to get it to do what you want
if i in message.content:
return await message.channel.send(ben_responseULTIMATE)
sends a message for every letter in any message
any tips on how to fix this?
You're going to get ratelimited really fast
hard to tell what you're trying to do
Do you want like trigger words that would make the bot say something?
yes
use a dict for it
pardon?
myDict = {
"triggerWord1": "answer1",
"triggerWord2": "answer2",
...
}
All your trigger words and answers are in there
and what would i put in the ben_responseULTIMATE
return await message.channel.send(ben_responseULTIMATE)```
in here
Then, in your on_message(), you can loop through each word, and check if that word is one of the keys in that dict:
myDict = {
...
}
for word in message.content:
if word in myDict:
print(myDict[word])
where would i put this
and for the answer, can i have a list?
Do you mean message.content.split()
Your current would iterate characters
oops yeah
within your on_message
async def on_message(myDict = {
...
}
for word in message.content:
if word in myDict:
print(myDict[word])):```
like so @sick birch ?
euphoria read this
so it should be message.content.split(myDict = {
...
}
for word in message.content:
if word in myDict:
print(myDict[word])
print(myDict[word])):
nono, you need to use the for loop kn message.content.split
how would i do that
for word in message.content.split(' '):
...
That loops through each word in the message
From there you can check if word in myDict
async def on_message(message):
for word in message.content.split(' '):
???, sorry if im coming of as really stupid, i am
Thats the first part correct
Now you need to fill in the block of the for loop
for word in message.content.split(' '):
# logic here
it's discord
they never changed the namespace
async def on_message(message):
for word in message.content.split(' '):
if message.author.bot: return
for i in ben:
if message.channel.category.id == 928088528754192446:
return
if i in message.content:
return await message.channel.send()```
something like this? if not then what do i need to replace
You can move the if message.author.bot: return outside of the loop
Same thing with if message.channel.category.id == 928088528754192446: return
async def on_message(message):
for word in message.content.split(' '):
for i in ben:
if i in message.content:
return await message.channel.send()
for word in message.content.split(' '):
if word in myDict:
# send a response using myDict[word]
else:
# ignore, no trigger word
i cant use ctx.send can i
ctx isnt defined, which is why i asked
doesn't split have ' ' as the default argument already?
message.channel.send is what you would use
I'm pretty sure it's required
!e print("a b c".split())
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['a', 'b', 'c']
ig not
Okay I think I finally resolved my issues with installing pycord except when I installed some of the boilerplate code from the examples folder on their github I am already getting resolution errors as if the discord object I am importing is different from the one they are using:
"ben": "yes"
"ben"; "no" }```
restart vscode,
do you have some other libraries using the discord namespace?
getting the statements are not closed, and expected expressions error
"ben"; "no" } should be a colon, and you can't have 2 same values in a dictionary
so i cant have it cycle through 4 responses for the same triggerword?
use a list or tuple! py my_dict = { "ben": ("word1", "word2", "word3") }
I have and I did have discord.py which was registered under the same namespace. I uninstalled both py-cord and discord.py. After I made sure I no longer had import discord and checking the pip list I then re-installed py-cord and now have the ability to import discord. Unfortunately the code in the example does not work in my project.
i have to pick? wdym
did you restart vscode?MissingImportsError is a well known glitch in it
I have restarted
with that i get this
Right, you have to pick one of those
you want to send a random one of these?
so i cant have it choose randomly
You can
yes sarth
random.choice()
!d random.choice use this
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
Can I just download the discord folder from pycord's github and drop it into my workspace instead?
well yeah you can
ill suggest using a venv instead
where would i put 1random.choice()
How long does it take to set up
a few seconds
async def on_message(message):
for word in message.content.split(' '):
if word in myDict:
await message.channel.send;random.choice()(myDict[word])```
$python -m pip install virtualenv
$python -m virtualenv <your env name>
# for linux/macOS
$source <your env name>/bin/activate
# for windows
$cd <your env name>
$.\Scripts\activate``` and then you can pip install in the venv
.send(random.choice(myDict[word]))
much thanks
Hello lads
Pretty sure it is discord.ext.commands
from discord.ext.commands import slash_command```
You had no issues with libraries
how to change this version ?
Because no versions of discord match >1.7.3,<2.0.0
and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
So, because python-template depends on both discord (^1.7.3) and aiohttp (^3.8.1), version solving failed.
they removed exts, its just discord.commands now
👀
who
because i can tell you for a fact that discord.ext.commands still exists
What did you try to install
i tried to import aiosqlite and aiohttp
His from discord.ext import commands gives no errors
Maybe different version
The solution would be to add ext anyways
And what version of dpy do you have
1.7.3
Try installing 2.0
oh nevermind, i was talking about pycord they didnt remove it, but discord.commands should still work
don't think that would be helpful since slash commands for cogs are implemented under the discord.commands folder
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_cog.py at master · Pycord-Development/pycord
this is the example they are using it im not wrong
if message.content contains link:``` how do i make this work properly with api
You could use in in your if-statement
well i am meaning like this
!e
string = 'https://twitter.com'
if 'https://' in string:
print("Found")
@high sun :white_check_mark: Your eval job has completed with return code 0.
Found
oooooooooh thank you
you should know how to do this already
i haven't messed with that in a long time if ever
whats with the spoonfeed? you already gave them some pseudocode
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (c:\Users\ghost\PycharmProjects\pythonProject4\venv\lib\site-packages\discord\channel.py)
tf is this? didnt change anything
where does this error come from?
i know how to use in i didn't know if we had a contain function or not
I explained in the previous message, I'm allowed to do so right?
cool :D, well, contain exists but you would not like using it
There's no rule saying you can't spoonfed
i mean the source of error, could you send the complete traceback and related code?
good to know now i'm on webhooks on making a sending webhook command for updates
Which lib are you using?
pycord
how to use hybrid_command ?
of course, but they won't learn anything if you spoonfeed
well i learn from examples so it was really helpful and it makes it so i don't got to come back about the same thing
Perhaps you have multiple discord libraries installed
I dont
I didnt change anything, bot was running and after a while that error came
from discord import Webhook, AsyncWebhookAdapter
import aiohttp
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session))
await webhook.send('Hello World', username='Foo')``` what is foo?
Well, that would be the thing that causes the error
Well, try it and you'll find out what or who is 'Foo' if you're talking about the username
A function
yes, but it isn't tolerated here
he didn't spoonfeed
I know?
he showed an example using the !e function
ye
how do i make it so i need to use a command in the bot dms and it doesn't work anywhere else? docs link by chance?
check is ctx.channel is an instance of discord.channels.DMChannel
ok i'll check but that should work
docs doesn't make alot of sense on how to make it work can you explain the docs?
Are you using on_message or a command?
Problem with firewall ig
i can do either
thinking command though on_message if i have to
You can do an if-statement in either of them
If you’re using on_message you can do a simple if-statement
yep
Just check on ID
!d discord.on_message
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...
the hard way ok
!d discord.Message
class discord.Message```
Represents a message from Discord...
Did you found it, @echo wasp ?
!d discord.channel.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel...
The given argument of on_message is message
@echo wasp do something like if isinstance(ctx.channel, discord.channel.DMChannel): ...
So check the channel ID of the message
u can check the channel of that too message.channel
i did py @command.commands() async def webhook(self,ctx): await ctx.send(f"id is {ctx.channel.id}")
I didn’t want to spoonfeed that much hahah
showing the right way is not spoonfeeding
ur telling to check the id, that is not right
I know, but I wanted him to figure it out himself by giving the class
i never knew the id of a dm channel so how do i check a channel i have no idea what the id is
You want it hard coded or the id of the channel of ctx?
dont check the id, check if the type of channel is discord.channels.DMChannel
If you’re wanting the bot to work in a specific channel you have to
they only wanted it to work in dms
now i just run a check to make sure the channel matches and then i'm good to go and i'm hard coding a webhook sender for updates
a dm
👀
what is the username slot filled with on the webhooks
i gues u can do this if isinstance(ctx.channel, discord.channel.DMChannel) and ctx.author.id == <user_id>
i had it print the id of the dm channel
um then use that
What do i fill the username slot with on the webhook example they give you?
what username slot?
from discord import Webhook, AsyncWebhookAdapter
import aiohttp
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session))
await webhook.send('Hello World', username='Foo')```
that one
^^^^^^^^^
You can't use a webhook to send a DM
no
i'm making a command where i enter in a kwarg that sends in the webhook to a channel in a server and publishes it
await fetch_webhook(webhook_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook "discord.Webhook") with the specified ID.
Changed in version 2.0: `webhook_id` parameter is now positional-only.
is a webhook counted as a bot?
Webhook is webhook wdym
working on embeds?
it means right next to the other feild if inline is false it goes underneath it
and i don`t know what is inline
thx
only affects the ones after the first feild you have
len(list(filter(lambda x: x.bot, guild.members)))
thx
i had to get help on that one aswell
File "/home/runner/Mavic-New-1/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 693, in _parse_arguments
raise discord.ClientException(fmt.format(self))
discord.errors.ClientException: Callback for balance command is missing "ctx" parameter.
@commands.command(aliases=['bal'])
async def balance(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title=f'{ctx.author.name} Balance',
color=discord.Color.red())
em.add_field(name="Wallet", value=wallet_amt)
em.add_field(name='Bank', value=bank_amt)
await ctx.send(embed=em)
is anything wrong in this ?
Are you using classes?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed...
when I write None it says so
Hello, I'm looking for some help, in my discord bot, I create a text channel on the server, but I would like to get the id of the channel I just created to use it later on, any way I could do that please ?
uhhh
I'm not sure you want to see it but let's go
@bot.command()
async def rejoindre(ctx,royaume):
if partie_on == True:
if royaume in royaumes[1:7]:
identif = ctx.author.id
try :
pickle_ouverture = open (f"fiche de {identif}","rb")
if load(ctx.author.id)['royaume'] == royaume:
await ctx.send("Tu as déjà rejoint ce royaume.")
else:
await ctx.send(f"2")
fiche = load(ctx.author.id)
await ctx.author.remove_roles(discord.utils.get(ctx.guild.roles, name = fiche['royaume']), atomic=True)
fiche['royaume'] = royaume
save(ctx.author.id,fiche)
await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name = royaume), atomic=True)
tep(ctx.author.id,"".join(['c',royaume[0].lower()]))
liste = load("".join(["liste_",fiche['royaume']]))
liste.remove(ctx.author.id)
save(liste, "".join(["liste_",fiche['royaume']]))
liste = load("".join(["liste_",royaume]))
liste.append(ctx.author.id)
save(liste,"".join(["liste_",royaume]))
await discord.utils.get(ctx.guild.channels, id = categories_royaumes[royaume]).create_text_channel(name='{}'.format(f'fiche-{ctx.author.name}'))
await ctx.send(f"{ctx.author.name} a bien rejoint le royaume de {royaume}")
return
except :
await ctx.send(f"1")
dico_joueur = {'hp':3,'po':500,'tp':0,'mont':montures[0],'role':roles[0],'comp':competences[0],'bgmt':[bourgs[0]], "royaume": royaume}
save(identif,dico_joueur)
await discord.utils.get(ctx.guild.categories, id = categories_royaumes[royaume]).create_text_channel(name='{}'.format(f'fiche-{ctx.author.name}'))
await ctx.send(f"{ctx.author.name} a bien rejoint le royaume de {royaume}")
await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name = royaume), atomic=True)
tep(ctx.author.id,"".join(['c',royaume[0].lower()]))
try:
liste = load("liste_joueurs")
liste.append(ctx.author.id)
save("liste_joueurs", liste)
except:
liste = [ctx.author.id]
save("liste_joueurs", liste)
try:
liste = load("".join(["liste_",royaume]))
liste.append(ctx.author.id)
save("".join(["liste_",royaume]), liste)
except:
liste = [ctx.author.id]
save("".join(["liste_",royaume]), liste)
return
else:
await ctx.send(f":warning: {royaume} n'est pas un royaume. Attention à l'orthographe, la liste des royaume est: {', '.join(royaumes[1:7])}")
return
!code
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.
U forgot self
u can do ctx.channel.id there
The channel which I want to get the id is the channel I create in
await discord.utils.get(ctx.guild.categories, id = categories_royaumes[royaume]).create_text_channel(name='{}'.format(f'fiche-{ctx.author.name}'))
not the channel in which I write the rejoindre command
a = await discord.utils.get(ctx.guild.categories, id = categories_royaumes[royaume]).create_text_channel(name='{}'.format(f'fiche-{ctx.author.name}'))
print(a.id)
not sure but try
kekw it works thanks
btw why not use f string?
what did I copy paste
u used f string in . format
yes
a friend of mine told me to use the f thing for channel names I think
so I used it
You should learn python before getting into discord bots........
writing a discord bot is my way of learning python
this bot will probably never run on a real server
it's just a training dummy
a very bad way indeed
I do understand python lmao
hm
if you did you would be knowing bout f strings
I do know about f strings I use them in my code
..
I just didn't know they were called f strings
anyway my question was answered theres literally no reason for us to talk
so why are u using .format
this part was copy pasted from my friend
whats the issue?
dpy 1.7.3 doesnt have official support for slashes
hes not accepting that he dont know python
Sparky stop
not knowing about f-strings does not mean that the individual has no python knowledge
at the end of the day they are sent just like msgs so..... it should be able to right?
bots can't use other bots' slash commands
well, you can use third party libraries
..
only users can
Which one?
!d discord-py-slash-command
No documentation found for the requested symbol.
that will work?
??
A slash command handler for discord.py.
its just how u do selfbotting
use this library if you want to but i recommend upgrading to 2.0 @tiny ibex
how to send a command is what i am asking!
huh?
there is no example on how to do that!
send a command....?
oh my god did you read my question?
yeah...
listen bot cant use slash commands
thats it
you wanted another bot's slash commands....?
what......?
he want to run a slah command of another bot with his bot
idk
yes

how does the discord client do it.......
dont selfbot
tf?
you cant run commands of other bots using your bot
there are some things meant to be limited to user accounts only
app commands, profiles, badges, connections, friends being some of them
ok
What
Then why would you ask
Cuz my wish -_-
anyways
wanted to create something like discurses
what even is discurses
i get this error whn i type self
File "/home/runner/Mavic-New-1/cogs/economy.py", line 35, in balance
await open_account(ctx.author)
File "/home/runner/Mavic-New-1/data.py", line 32, in open_account
await loop.run_in_executor(None,inthread)
AttributeError: 'builtin_function_or_method' object has no attribute 'run_in_executor'
def inthread():
try:
glock.acquire()
with open('mainbank.json','w') as f:
json.dump(users,f)
finally:
glock.release()
loop = asyncio.get_running_loop
await loop.run_in_executor(None,inthread)
return True
mhm
How can I fix the error?
u do exactly as it says. "names must be all lower case"

how
the error occurs when I run the bot
"names must be all lower case"
❌ name=Ban
✅ name=ban
Lowercase
o
ty
np
helo again
I have a problem with a command
@bot.command()
async def fiche(ctx):
if partie_on == True:
if int(ctx.channel.id) == int(load("identifiants_fiches")[ctx.author.id]):
a = load(ctx.author.id)
inv = a['inv']
finv = ", ".join(inv)
eqp = a['eqp']
feqp = ", ".join(eqp)
embed=discord.Embed(title="Fiche Personnelle")
embed.add_field(name="Points de vie:", value=f"{a['hp']} :drop_of_blood:", inline=True)
embed.add_field(name="Pièces d'or:", value=f"{a['po']} :pofix:", inline=True)
embed.add_field(name="Trésorerie perso:", value=f"[ {a['pt']} :pofix: ]", inline=True)
embed.add_field(name="Rôles:", value=a['role'], inline=True)
embed.add_field(name="Compétence:", value=a['comp'], inline=True)
embed.add_field(name="Bourgmestre de:", value=a['bgmt'], inline=True)
embed.add_field(name="Localisation:", value=a['tp'], inline=True)
embed.add_field(name="Monture:", value=a['mont'], inline=True)
embed.add_field(name="pods:", value=a['pods'], inline=True)
embed.add_field(name="Ressources:", value=f"{a['fer']} :fer: / {a['pierre']} :pierre: / {a['acier']} :acier: / {a['bois']} :bois: / {a['herbe']} :herbe: / {a['argent']} :argent:", inline=False)
embed.add_field(name="Inventaire:", value=finv, inline=False)
embed.add_field(name="Equipement:", value=feqp, inline=False)
await ctx.send(embed=embed)
here's the error I get:
Ignoring exception in command fiche:
Traceback (most recent call last):
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\xxxxx\Documents\Perso\Perso\Python\bot furiat\bot.py", line 235, in fiche
await ctx.send(embed=embed)
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.10.value: This field is required
In embed.fields.11.value: This field is required
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python310\lib\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: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.10.value: This field is required
In embed.fields.11.value: This field is required
the problem seems to be the .join() format
load("identifiants_fiche") is a dictionary of lists
print(a[inv])
nw
!d discord.ext.commands.MissingRequiredArgument
exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter
that is required is not encountered.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
Use this error to send what you want
I think you can do
async def command(ctx, argument='something')
if argument == 'something':
send your error
Would work but it's better to use this
= -> assignment operator
== -> equality check operator
I'm assuming you're using commands.Bot so the naming doesn't affect it but you should still name it bot for good naming practice
ok i will try it
i want to do something like
if argument == null:
await ctx.send("Enter A String")
i just want to check if the argument is empty and if it is then give error
That is what commands.MissingRequiredArguments does
Just have a error handler
can you give me a code example? (sorry to annoy 😅 )
@your_command_name.error
async def your_command_name_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Missing required argument")
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1651230820:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
thank you so much!!
Because no versions of discord match >1.7.3,<2.0.0
and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
So, because python-template depends on both discord (^1.7.3) and aiohttp (^3.8.1), version solving failed.
i just imported aiohttp i got this error
Disregard. I misread the docs
@bot.command(name='button')
async def button(ctx):
await ctx.send(
"Hello, World!",
components = [
Button(label = "WOW button!", custom_id = "button1")
]
)
interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1")
await interaction.send(content = "Button clicked!")
I keep getting "This interaction failed"
Oof
2f3136
Use buttons from disord.py 2.0
Can you please direct me towards the docs?
Buttons (or components) are now in the 2.0a version of the library which is only obtainable from GitHub.
If you wish to use Buttons (and Selects/Dropdowns), please view the documentation for discord.ui here: https://discordpy.readthedocs.io/en/master/api.html#bot-ui-kit
You can also view examples in the repo: https://github.com/Rapptz/discord.py/tree/master/examples/views
how do i get aiohhtp 3.6.0 ?
Installing collected packages: frozenlist, async-timeout, aiosignal, aiohttp, discord2
Attempting uninstall: async-timeout
Found existing installation: async-timeout 3.0.1
Uninstalling async-timeout-3.0.1:
Successfully uninstalled async-timeout-3.0.1
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
discord-py 1.7.3 requires aiohttp<3.8.0,>=3.6.0, but you have aiohttp 3.8.1 which is incompatible.
Successfully installed aiohttp-3.8.1 aiosignal-1.2.0 async-timeout-4.0.2 discord2-2.0.1 frozenlist-1.3.0
pip install aiohttp==<version>
ty
you have aiohttp, and it shouldnt really be much of a problem if you hae a higher version
but the bot dosent run
weird
Um remove the author name?
yes its fine, and you dont need to typecast a string to a string
Why do u have it there if u don't want?
How can I install it via pip?
im not able to use py2.0
Well am trying to make a profile command and like storing data in a db
it says some aiohttp version dosent match
py -m pip install git+https://github.com/Rapptz/discord.py
How do u remove embeds on phone 😢
Updating dependencies
Resolving dependencies...
SolverProblemError
Because no versions of discord match >1.7.3,<2.0.0
and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
So, because python-template depends on both discord (^1.7.3) and aiohttp (^3.8.1), version solving failed.
at venv/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
237│ packages = result.packages
238│ except OverrideNeeded as e:
239│ return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
240│ except SolveFailure as e:
→ 241│ raise SolverProblemError(e)
242│
243│ results = dict(
244│ depth_first_search(
245│ PackageNode(self._package, packages), aggregate_package_nodes
/home/runner/Mavic-New-1/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
exit status 1
do u know wht is causing this im not able to figure it
who tf uses 2.0 now
replit uwu
which version to use ?
LMAO I thought they said dpy2.0
2.0 python came out in like 2006 bruh
3.8 or higher
how do i install 3.8 ?
pip install discord.py==3.8.0 ??
it'd like https://python.org
dpy doesn't have a 3.8?
So?
yeah iirc it only has 2.4.0 rn
what?
Aliases possible in command group?
your memory is bad
yes
Any example?
I know :)
You can fix this by actually calling get_running_loop
async def start(ctx):
embed=discord.Embed(title="Profile", description="", color=0x00ff00)
embed.add_field(name= f"User: {ctx.author.mention}", value="✅Verified 18+✅", inline=False)
embed.add_field(name='Name', value=str(ctx.author.name), inline=True)
embed.add_field(name='Age', value="", inline=True)
embed.add_field(name='Gender', value="", inline=True)
embed.add_field(name='Orientation', value="", inline=True)
embed.add_field(name='Location', value="", inline=True)
embed.add_field(name='Dating status', value="", inline=True)
embed.add_field(name='Height', value="", inline=True)
embed.add_field(name='DMs status', value="", inline=True)
embed.add_field(name='Verification level', value="", inline=True)
embed.add_field(name='Looking for', value="", inline=True)
embed.add_field(name='Hobbies', value="", inline=True)
embed.add_field(name='About me', value="", inline=True)
embed.set_author(name=ctx.author.name, icon_url= ctx.message.author.avatar_url)
await ctx.send(embed=embed)```
() pls
Is this right?
Try It And See
Um?
.
Never used aliases
@commands.group(aliases=["1", "2", "3"])
Please help me while i playing next song in queue i got this error
TypeError: on_wavelink_track_end() missing 1 required positional argument: 'player'
This is an wavelink track end code
async def on_wavelink_track_end(ctx: commands.Context, player: wavelink.Player, track: wavelink.Track, reason):
ctx = player.ctx
vc: player = ctx.voice_client
if vc.loop:
return await vc.play(track)
next_song = vc.queue.get()
await vc.play(next_song)
await ctx.send(f"Now playing {next_song.title}")```
Ty
async def start(ctx):
embed=discord.Embed(title="Profile", description="", color=0x00ff00)
embed.add_field(name= f"User: {ctx.author.mention}", value=":white_check_mark:Verified 18+:white_check_mark:", inline=False)
embed.add_field(name='Name', value=str(ctx.author.name), inline=True)
embed.add_field(name='Age', value="", inline=True)
embed.add_field(name='Gender', value="", inline=True)
embed.add_field(name='Orientation', value="", inline=True)
embed.add_field(name='Location', value="", inline=True)
embed.add_field(name='Dating status', value="", inline=True)
embed.add_field(name='Height', value="", inline=True)
embed.add_field(name='DMs status', value="", inline=True)
embed.add_field(name='Verification level', value="", inline=True)
embed.add_field(name='Looking for', value="", inline=True)
embed.add_field(name='Hobbies', value="", inline=True)
embed.add_field(name='About me', value="", inline=True)
Can someone help me
sureee
but.. what help u need? :")
what error you got?
or are u just showing your code? :")
If that’s actually your code
You can’t use it because all your fields values are empty
Ok well it suppose to be cuz i am storing data into the db
and i want it to show
in case u want to MAKE IT LOOK LIKE empty, just put its value as ** ** it works lol
OK well i am trying to add ppls age as an embed profile
sry was afk, just remove the value=
Discord fields require a name and value
u can't add fields without values?
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: This field is required
damn
value is required.. even i didn't know
just got to knwo about it a few minutes ago when tylerr told
but this works if someone wants to make it LOOK LIKE EMPTY :>
uhml... i've never used sqlite.. but see the examples & use SQL?
for testing purpose u can add any data for now.. just to test how your embed gonna look like
why are you gonna try to use a sql based database without knowing sql
That’s like the same principle as trying to learn dpy with no python knowledge
It’s literally the same thing as any other database
yeah just connector & execute, fetch things..
cursor
Yeah but i have knowledge on python
you need a cursor
😂 in asyncpg i ain't using cursor.. but in mysql, i use
just look up their docs
there should be some demonstration of how ot use it
i'm only familliar with asyncpg & mysql-connector-python
sqlite is easy too if you know how to use it
i just never looked into it, tho i'm sure i'll get its grip (if i ever feel like i need to use it )
well i can agree
postgres took me like hours to get its grip tho i was already familiar with mysql
uhm... i would suggest.. to learn from docs, freecodecamp videos (they're good for starters, tho idk if they've any video for this) and stuff...
So here’s the thing
I got my bot prefix as a? I want the bot to respond to a? & A?
Possible?
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result
anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with
this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality
to manage commands...
case_insensitive = True
``` @slate swan
That's for commands
That applies to commands
!pip aiosqlite
For async sqlite
🤔 can't be for prefix?
No literally just set a second prefix
No, it's only for commands
command_prefix = [prefix_1, prefix_2]
sqlite3 is a package that is installed with python. aiosqlite is a library for asynchronously working with a sqlite database
Like this add yr prefixes
i would suggest u to go with what i suggested.. it will work
they have to be strings
Dude, it's only for command names, not prefixes wth
🤔 it doesn't work for prefixes?
!d discord.ext.commands.Bot.case_insensitive
Whether the commands should be case insensitive. Defaults to False. This
attribute does not carry over to groups. You must set it to every group if
you require group commands to be case insensitive as well.
"Whether the commands should be case sensitive"
aahh looks like i've forgotten about prefix command shit.. since i moved to slash 😭
💀
That's what I'm tryna tell u since the start smh
😔
😭
uhm... thank u :>
slash = trash
con = sqlite3.connect('example.db')
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS AGE
(age text)''')
con.commit()``` Am i on the right track?
Not funny
I can imagine.
okay?
Seems like it
actually i was saying thank u to u, so i said "u too"
Aaaa
but.. it went wrong.. so nvm
Bad context.
I thought u meant to reply to the message "slash = trash"
💀 bruh
My bad
I can acknowledge the fact I’m trash too
ok whatever u wanna think :")
Since u edited it too
Helo again, I put a discord.py command in a function which wasn't in async, it it very dangerous ? or I can leave 1 or 2 discord.py commands in non-async functions
def tep(target, destination='∅'):
fish = load(target)
channel = bot.get_channel(channels_bourgs[fish['tp']])
fish['tp'] = destination
save(target, fish)
overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
cible = bot.get_user(target)
channel.set_permissions(cible, overwrite=overwrite)
Error:
c:\Users\xxxxx\Documents\Perso\Perso\Python\bot furiat\bot.py:331: RuntimeWarning: coroutine 'GuildChannel.set_permissions' was never awaited
channel.set_permissions(cible, overwrite=overwrite)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
i can acknowledge the fact that slash are trash to some point
await
U forgot to await
but still they make things somewhat easier
I agree
guys read my text pls 💀
which one? 💀
this one 💀
oh nvm i'm blind 😂
That won't work
well it does
Python error. U can use await inside an async function
I didn't await and I used it in a non-async function
so it still did the stuff, but I got an error
only thing that’s relatively good about slash commands is the auto-complete aspect
That’s the only thing that regular message commands won’t be able to beat
And probably the pre-set answers
well u can also set minimum & maximum value for integer type input... so it saves a bit of your code lines..
and it tells user automatically what it is expecting as input (if you've description for that input)
and u can set input whether it shuold be optional or required..
so.. 👀 it is a life saver in some ways
what if it does
uhmm.. can we say that it make things user friendly?
tho yeah.. a lil bit pain for devs :")
P.S: Im aware that some ppl are still struggling with using slash rn.. but eventually they all will move towards it
So it set the permissions without you having to await it
That’s crazy .
I doubt that’s what happened
no no
Python won’t let that happen.
Definitely not
u can ping btw. i don't bite
Message commands all the way to the end 
Force of habit
😂 alright
🛐 somewhere even i wish for the same
hello
ok look
@slate swan ```py
@client.event
async def on_message(message, searchKey):
if searchKey in message.content.lower().strip():
await message.delete()
in a code
may i suggest something like this? this way u dont need more events
searchkey?
umm, where must I put my message
my words
ohh wait nvm
discord.py doesn't pass anything else to on_message but the message
also, probably should also use snake_case 😅
yeah i realized haha
Hi again
async def tep(target, destination='∅'):
fish = load(target)
channel = bot.get_channel(channels_bourgs[fish['tp']])
fish['tp'] = destination
save(target, fish)
cible = bot.get_user(target)
await channel.set_permissions(cible, send_messages = False)
(the problem isn't channel because everything works when I replace set_permissions with send("test")
You passed in a mention right?
)) but why if I said this, it actives only second
@client.event
async def on_message(message):
if "lol" in message.content.lower():
await message.delete()
@client.event
async def on_message(message):
if "haha" in message.content.lower():
await message.delete()
I'm not sure what that means
Something like
!tep @small sentinel
would work
It won't work if you're doing !tep Ukos
the second one is over writting the first one
ohh, then what are you passing to the function?
Than, how to do both (I need both)
passing = arguments given ?
if so target is a user id and destination is a string
i feel like (no offense) u dont understand whats going on, just pretty much asking us to write your code for you
this is purely an observation and i wish u luck with it, but i strongly recommend you learn more python first, just for your own good to avoid countless headaches
me ?
they're not asking for code
something like if any( i in ['lol', 'haha'] for i in message.content.lower().split() )
or uh, why not just do message.content.lower() in ["lol", "haha"]
^^
Then I don't think the code you sent was the cause of the error
!e
print('hello world' in ('hello', 'world'))
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
False
oh yeah
i c the prob, i forgot to split in my example
should I send the whole error message ?
Sure ig
Back
Ignoring exception in command tp:
Traceback (most recent call last):
File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\achil\Documents\Perso\Perso\Python\bot furiat\bot.py", line 333, in tp
await tep(target, destination)
File "c:\Users\achil\Documents\Perso\Perso\Python\bot furiat\bot.py", line 320, in tep
await channel.set_permissions(cible, send_messages = False)
File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 648, in set_permissions
raise InvalidArgument('target parameter must be either Member or Role')
discord.errors.InvalidArgument: target parameter must be either Member or Role
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\achil\AppData\Local\Programs\Python\Python310\lib\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: InvalidArgument: target parameter must be either Member or Role
^
Code
CODE PART 1
CODE PART 2:
@bot.command()
async def tp(ctx, target='∅', destination='∅'):
await tep(target, destination)
(target is a user-id and destination is a string)
The error seems to be about the parameters of the set_permissions function but cible is a user so I don't understand why he isn't happy
Is there any way to scrape members from a Discord server?
Guild.fetch_members()
Using discord.py, right?
yes
i'll someone else take it from here, ashley or hunter, since i have a geo test
do yk how to check the onne who clicked on the button im using on message event + and i subclassed the disnake.ui.View
@client.command()
async def operator(ctx):
m = await ctx.send(content="Loading calculator")
expression = "None"
delta = datetime.utcnow() + timedelta(minutes = 5)
e = discord.Embed(title="Basic Operation Calculator",description=expression)
await m.edit(components=buttons, embed=e)
while True :
res = await client.wait_for("button click")
while m.created_at < delta :
if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
expression = res.message.embeds[0].description
if expression == "None" or expression == 'An error occurs':
expression = ''
elif res.component.label == 'Exit':
await res.respond(content='Calculator Closed. Thanks for using Basic Operation Calculator.',type=7)
break
elif res.component.label == "←":
expression = expression[:-1]
elif res.component.label == 'Clear':
expression = None
elif res.component.label == '=':
expression += calculator(expression)
else:
expression = res.component.label
f = discord.Embed(title='Basic Operation Calculator',description=expression)
await res.respond(content='', embed = f, component=buttons, type=7)
no errors in console
button says interaction failed
await defer(*, ephemeral=False, with_message=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
do this if the process takes longer than 3 seconds
@bot.bridge_command(description = "Just testing")
async def test-one(ctx):
embed = discord.Embed(
description="Test Accomplished! 😎",
colour=discord.Colour.teal()
)
await ctx.respond(embed=embed)```
why when i do `async def test-one` it doesnt work, but when i do without the dash (`testone`) it does.. how can i use two words? 
With an underscore: _
Also known as snake_case
A helpful link regarding naming as well: https://peps.python.org/pep-0008/#naming-conventions
discord.ext.commands.errors.CommandNotFound: Command "buy-crypto" is not found hmm doesnt seem to work
you can only have one on_message function
^[^\d\W]\w+ 😳
also you need to add client.process_commands(message)
Again, that is a -, not a _
oh but in the actual command, id want it to be like ?buy-crypto
is there a way to use a dash and not an underschore
if you want to use a space
then do this
put it in the aliases
What is the official Discord API through which I can fetch members of any discord server?
@bot.command(name='buy-crypto', aliases=['anything'])
@bot.command()
async def buy(ctx: commands.Context, option: str):
if option == "crypto":
do-this
elif option == "something-else":
do this instead
but its for the py async def buy-crypto(ctx): 😅
hmm.. is there no easier/smaller work around? 😅 as there's be like 40 commands
Someone please help
use aliases like he said
sorry, im a little confused how thatd work
@bot.command(name='buy-crypto', aliases=['anything'])
async def test_one(ctx):
embed = discord.Embed(
description="Test Accomplished! 😎",
colour=discord.Colour.teal()
)
await ctx.respond(embed=embed)
@bot.command is a decorator
remove the - is not a valid name in python
it modifies your function so it works as a command
so pass in aliases
which are alternative names for your command
guild = client.get_guild(GUILD ID)
for member in guild.members:
print(member)
hmm
aah brilliant, thx! it works for the prefix command, tho for the slash command it displays with an _, it there maybe like a idk hex code or somma for a - so i can make the slash look like /buy-crypto 😅
I need to use discord.py for this right? Sorry but I am a noob in coding.
yes
no
you can use any wrapper you want
or pycord
is there no way to use it 
hmm
wait
can i do somma like dash = - i mean i doubt itd work tho lol
slash commands does not allow - in their name
import discord
intents = discord.Intents.default(members=True)
client = commands.Bot(command_prefix = prefix, intents=intents)
class MyClient (discord.Client):
async def on_ready(self):
guild = client.get_guild(server id)
print ("ich bin online beep")
for member in guild.members:
print (guild.members)```
Will this work?
ooh.. so is their maybe a way to add a space for the slash command?
server id is not given
you have to specify it
its called a slash command group, where buy would be the command, and crypto would be a subcommand
@bot.slash_command(name="buy-crypto", description="Buy some crypto!")
async def _buy_crypto(inter: disnake.ApplicationCommandInteraction):
await inter.response.send_message(f"Hello {inter.author.mention}!")
cur.execute('''INSERT OR IGNORE INTO AGE VALUES ('1','2','','','')''') is this where i would add number values?
and i dont think you need the class for this
aah, okay, i'mma try that thx
what exactly are you trying to do
you dont make 2 client/Bot instances in the same bot
Okay, let me try. Will be back in a minute.
Also, Thank You So Much for your help.
i think i;mma like a group 😉 ty!
ill send you what you need, but what are you trying to do
All I want to do is scrape members of a particular Discord server.
try :
@bot.group()
async def test(ctx):
pass
@test.group()
async def one(ctx):
await ctx.send("Hello")
with a bot or with a normal account

Please can you suggest the right code? Will be great help.
Normal account
yeah thats against tos
back
Please can you suggest the right way to do it?

make a bot
botting with normal accounts is completely against tos
unless you use a bot you're gonna get banned
is @limber stratus alt ?
he'd have to invite it to the server he wants to scrape
1st declare a bot class ```py
from discord.ext import commands
bot = commands.Bot(command_prefix="your prefix")
and then simply make an eventpy
@bot.event
async def on_ready():
do your stuff```
that wont work
why?
he's trying to use a user account
that's against Tos then
apart from it being against tos
self-botting ⁉️
that also wont work
that will,
🕵️
nope
explain
Damn, this is confusing.
first of all most wrappers stopped supporting selfbots
so you need to use an older version
discord.py 1.7.3 the current version of discord.py does, next?
self-botting is making your account into a bot
second you need to pass in some extra arguments to commands.Bot and bot.run
HI
you also cant use commands like you do with a bot
i didnt mention the arguments for that purpose, if you can see it
dont selfbot its against tos
it is
yeah i know
watch some tutorials on how to make a bot
👍
he doesnt know python
😂 i wasnt correcting you, i just said yeah, it is
ye idk
he needs to learn that first
sparky with his message edits
lol
😎
Okay so first I need to create a bot first.
Then will I be able to scrape members from any discord server?
ok ill show you exactly what you need to do
any discord server your bot is in
Is self bot allowed?
for a bot
never
nope never
nope
now dont
Please, you are GOD in disguise
Yeah I won't now haha
real chads use self bots to edit their messages 100 times a second
import discord
from discord.ext import commands
prefix = "!"
bot = commands.Bot(command_prefix=prefix)
@bot.event
async def on_ready():
print(f"Logged In As {bot.user}")
@bot.command()
async def members(ctx: commands.Context):
for member in ctx.guild:
print(member)
bot.run("token")
lmfao
then go to https://discord.com/developers/applications
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
do you know how to invite bots and get their token?
log in and click new application
reply :detective: if ur expert in python and think that none can beat you
🕵️
my failed creations 😔
except joy
🐲
you cant
i have 2
what?
u can
you cant delete a bot, but you can delete the application and the bot gets deleted automatically
i see

lol
!remix
!code
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 use discord.py
copy paste
yeah
not that
use jishaku :D
!pip jishaku
A discord.py extension including useful tools for bot development and debugging.
