Discord.py how to get a server's id?
If your bot is receiving commands, then you can resolve the server the command is from through the message that invoked the command. When I use the command it sends "property object at 0x000001988E164270" instead of a list of server names Solution: is a list of all guilds that the bot is connected to.
Discord.py how to get a server's id?
I'm trying to set up unban but I'm not sure how to get a server's id to make it work. How would I go about getting the server's id?
Solution:
One way would be to enable Developer Mode in your discord client, and copy the ID from there. Follow the instructions here, then right click on the server icon and choose Copy ID from the context menu.
If your bot is receiving commands, then you can resolve the server the command is from through the message that invoked the command. For example:
This doesn't do any validations such as permission checking, checking the bot has permissions, or checking that the user is actually banned, but it should be enough to get the idea.
Get server ID in discord.py rewrite
Im trying to figure out how to get a server ID in discord rewrite so that I can save specific settings on an individual server- level basis. Is there anyway to do this?
Solution 1:
If you're collecting context from the original message/command, then you can use ctx.guild.name to return the name or ctx.guild.id to return the ID of the guild where the command was posted.
Solution 2:
If you want to storage any data I recommend to you JSON files Simply (to get server (guild in rewrite) ID: if command:
if event (e.g. on_member_join()):
if you wanna to save that into json file you could:
It will dump a data to JSON file. In this files it will be look like:
With this method you can save as much as you want
How to store server and user ids in json file with discord.py
Yo, so I'm trying to give the bot I'm building more useful configuration per server. But I use channel name right now because I don't know how to automatically get all server and channel ids and store them in a json. My question is, how would i use json to implement a guild config and make the bot automatically fill out the ids of each guild and channel it is in so as to code my bot to use that to set up the channels the bot uses?
My bot is built using discord.py rewrite if it helps.
Here is bot.py file with the functions I'm using for my config.json in it.
I'm wanting to add the function to this if possible.
This is my config.json if it helps
The API TOKEN parts are not being used rn, they are being reserved for a future update.
Thanks so much for the answer provided by Smoliarick
This is my slightly edited version if anyone else wants to use it. Editing it into the main post so people will be able to see it easier =)
Solution:
Try this solution (minimal example). In result you will have json file where key is guild.id and value is list of channel.id in this guild:
How to get a list of servers my bot is in discord.py
I want to use a command that prints the list of servers my bot is in. This is what I have. When I use the command it sends "property object at 0x000001988E164270" instead of a list of server names
How do I get a server's ID with discord.py?
I’m not using discord.ext, just discord. I need to find the server ID that the bot is currently connected to. I’ve done some googling, but could only find 1 stack overflow question and the answer wasn’t helpful. I could really use this, thanks!
4 Answers 4
You didn’t specify how you want to get the server ID, so here is an example using the command, you get ID of server, where this command was used.
You can check it and output with print for example print(id) will give output like this:
Also you can just add ctx.send(id) and Discord Bot will send this ID to server chat. Discord guild id have integer type. Now you got ID and can manipulate with it. Read more about it here
Как получить id сервера discord py
I’m not using discord.ext, just discord. I need to find the server ID that the bot is currently connected to. I’ve done some googling, but could only find 1 stack overflow question and the answer wasn’t helpful. I could really use this, thanks!
4 Answers 4
You didn’t specify how you want to get the server ID, so here is an example using the command, you get ID of server, where this command was used.
You can check it and output with print for example print(id) will give output like this:
Also you can just add ctx.send(id) and Discord Bot will send this ID to server chat. Discord guild id have integer type. Now you got ID and can manipulate with it. Read more about it here
How do I get a server's ID with discord.py?
Here's a way to get the guild (server) ID without using discord.ext , assuming you're using:
to capture messages/commands in your bot.
message.guild.name and message.guild.id
Would hold the relevant information.
You didn't specify how you want to get the server ID, so here is an example using the command, you get ID of server, where this command was used.
You can check it and output with print for example print(id) will give output like this:
Also you can just add ctx.send(id) and Discord Bot will send this ID to server chat. Discord guild id have integer type. Now you got ID and can manipulate with it. Read more about it here
Как получить id сервера discord py

Сегодня мы сделаем такой функционал:
Выдача роли при заходе на сервер, выдача роли по реакции
Бан, очистка сообщений
Поработаем с базой данных
Затронем API.
Так-же прикреплю полностью рабочий код в конце данной статьи.
База
Думаю как установить python вы разберетесь.
Прописываем в консольку:
Импортируем все нужные нам для данного гайда модули, а так-же задаем нужные нам интенты.
Но где мне взять токен и включить интент?
Заходим сюда > discord.com/developers/applications/
Тыкаем по стрелочкам.


Дальше нам нужно немного пролистать вниз и нажать воть сюда

Чтобы узнать токен жмем сюда

И сразу вставляем его вместо ваштокен.
С начальной подготовкой мы справились и переходим к следующему шагу.
Next Level – Код бота:
Начнём мы с самого простого – команды для модерации сервера.
Сделаем очистку сообщений по заданному количеству, бан, а так-же роли по клику на реакцию.
Лично я буду добавлять ко всем данным командам логирование в определенный канал, однако это совсем не обязательно.
Начнем с очистки сообщений.
А теперь разберемся и с баном.
Сделаем так-же выдачу роли при входе на сервер.
А так-же сделаем выдачу ролей по реакциям ведь это так круто!
Ну и бан сделаем.
А так-же чет захотелось сделать отправку эмбедов с discord.club (дабы отправлять эмбеды не залезая в код)
Теперь когда вы пропишите “!embed ” у вас отправится красивенький эмбед.
А теперь немножечко поработаем с БД.
База данных:
Создадим рядом с ботом файлик bd.json.
Теперь добавим туда следующее:
Переходим обратно к нашему боту и пишем функцию, которую будем использовать.
А теперь просто добавим в конце команды ban эту строку ( после await logs.send ):
Ну и на закуску мы сделаем статистику.
С БД я вроде закончил.
Ну и закончим нашу статью работой с API.
Api:
Мы будем работать с discord-tracker и проверять кто сидит с юзером в войсе + получать их айдишники.
(работать будет только если это на серверах, на котором есть бот discord трекера.
Useless, просто как пример использования х)
Как получить идентификатор пользователя в Discord.py
Мы пишем бота для нашего сервера Discord, который должен упоминать человека, который запускает определенную команду. Для этого мне понадобится идентификатор пользователя, но я не могу понять, как его получить.
Мы попробовали это так, поскольку в документации сказано, что идентификатор пользователя находится в классе User. Но единственное, что мы получаем, это
На наш взгляд, мы получили правильный параметр, но не можем получить само удостоверение личности? Мы должны преобразовать это как-то?
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account