Birthday bot discord настройка
Файл JSON, содержащий дни рождения:
Команда, которая сохраняет день рождения в файл JSON:
И команда, которая может прочитать кого-то bday, если вы пометите их как аргумент:
How to Add or Invite Birthday Bot on your server?
You can add the Birthday bot to your server by using the invite link: Invite . To properly add and set up the Birthday Bot follow the steps below.
STEP 1: Click on the Invite Button Above.
STEP 2: Select the server to which you want to add the Birthday bot.
STEP 3: Authorise the permissions that the Birthday bot requires to work properly.
STEP 4: Fill up the Captcha.
STEP 5: Return to the discord server where you have added the Birthday bot.
You have successfully added the Birthday bot on your discord server !!
Also, I will mention joining the support community group of Birthday bot so if you ever face difficulty with the bot you can ask for help in the community – Birthday Bot Support Server .
Заключение
Вот и подошла к концу первая часть обучения, как вы могли заметить, создать бота, используя библиотеку discord.js очень просто.
Полезные и интересные команды
В предыдущем разделе я показал вам, как запустить бота и как писать для него команды.
Теперь я хочу поделиться с вами несколькими своими командами.
Не стоит пугаться большого кода, здесь всё предельно просто.
Создание бота
Теперь, когда вы установили все нужные компоненты, мы можем приступить к созданию самого бота.
Здесь всё просто. Переходим на портал разработчиков и нажимаем на кнопку с надписью «New Application» — она находится в правом верхнем углу.
В открывшемся окне вписываем имя бота, после чего, нажимаем на кнопку с надписью «Create».
На этой странице мы можем изменить имя бота, загрузить для него иконку, заполнить описание.
Теперь наша задача — воплотить бота в жизнь. Для этого переходим во вкладку «Bot».
Нажимаем на кнопку с надписью «Add Bot» и воплощаем бота в жизнь.
Поздравляю! Вы создали аккаунт для вашего бота. Теперь у него есть тег, токен, ник и иконка.
Написание кода
Для того, чтобы наш бот появился в сети и мог реагировать на команды, нам нужно написать для него код.
Существует множество вариантов для его написания: используя один файл, два, несколько, и т.д
Мы рассмотрим вариант с двумя файлами, так как его использовать очень легко и удобно, но у каждого варианта есть свои недостатки — например, у этого недостатком является сложность в написании начального кода.
Но не волнуйтесь, весь код вам писать не придётся.
Для начала, нам нужно где-то хранить основные параметры и информацию о боте.
Мы можем сделать это двумя способами:
- Создать отдельный файл
- Записать всё в константы
Разберём хранение параметров в отдельном файле.
Итак, создаем файл config.json
Вставляем в него следующий код:
* Для получения токена зайдите на портал разработчиков, перейдите во вкладку «Bot» и скопируйте его.
* Самым распространённым среди разработчиков префиксом является !
Далее нам нужно создать файл bot.js и вставить в него данный код:
Теперь создаём файл comms.js, в нём будут сами команды.
В нём должен быть следующий код:
Чтобы добавить больше команд — просто объявляйте больше функций и добавляйте их в список, например:
И вот, мы вышли на финишную прямую!
Осталось всего ничего — запустить бота.
Для этого открываем терминал и вставляем в него следующую строку:
Готово! Бот запущен и вы можете им пользоваться, ура!
Чтобы пригласить бота на свой сервер, воспользуемся нам уже известным порталом разработчиков.
Перейдём во вкладку OAuth2, пролистаем чуть ниже, выберем «Bot» и отметим нужные боту привилегии.
Существует два способа:
-
Заранее отметить нужные привилегии.
Итоговый код должен быть таким:
Чтобы указать несколько привилегий, мы должны перечислить их в квадратных скобках, через запятую:
* Все привилегии указываются заглавными буквами
Список доступных привилегий:
ADMINISTRATOR
CREATE_INSTANT_INVITE
KICK_MEMBERS
BAN_MEMBERS
MANAGE_CHANNELS
MANAGE_GUILD
ADD_REACTIONS
VIEW_AUDIT_LOG
PRIORITY_SPEAKER
STREAM
VIEW_CHANNEL
SEND_MESSAGES
SEND_TTS_MESSAGES
MANAGE_MESSAGES
EMBED_LINKS
ATTACH_FILES
READ_MESSAGE_HISTORY
MENTION_EVERYONE
USE_EXTERNAL_EMOJIS
VIEW_GUILD_INSIGHTS
CONNECT
SPEAK
MUTE_MEMBERS
DEAFEN_MEMBERS
MOVE_MEMBERS
USE_VAD
CHANGE_NICKNAME
MANAGE_NICKNAMES
MANAGE_ROLES
MANAGE_WEBHOOKS
MANAGE_EMOJIS
2 ответа
Вместо использования setInterval , который на самом деле предназначен для повторения задачи каждые x миллисекунд, вы можете вместо этого использовать пакет узла под названием node-schedule, который в значительной степени предназначен для планирования на основе времени, а не планирования на основе интервалов. Это значительно упрощает планирование задач на определенную дату.
Вам также нужно будет удалить созданный вами новый Discord.Client в обоих ваших командных файлах; это не только не нужно, но и не будет работать так, как вы предполагали.
Решение
Это новый файл с именем birthdays.js , который находится в вашей основной папке (не commands ):
Это в основном файле вашего бота (например, index.js или server.js ):
Это файл вашей команды setbday :
Объяснение
Что касается обработчика событий ready в основном файле вашего бота, нам нужно добавить лишь несколько вещей. Сначала мы читаем ваш JSON-файл bdays, чтобы получить все дни рождения. Затем мы используем Object.values() , чтобы получить массив только значений файла JSON (помните, что формат вашего файла JSON - , что соответствует структуре JSON ). Затем мы перебираем все эти значения, используя Array.forEach() . Наконец, мы используем код из нашего файла birthdays.js , чтобы запланировать поздравление с днем рождения для каждого дня рождения, который мы просматриваем в файле JSON.
Если вы не поняли какую-либо часть этого кода или заметили какие-либо ошибки или что-то подобное, не стесняйтесь комментировать ниже и дайте мне знать!
Ответьте на вопрос в своем комментарии
Если вы просто хотите перечислить всех пользователей, у которых сегодня день рождения, вот полный код одного из способов сделать это (при условии, что это находится в командном файле, таком как ваша команда bday ):
Вы можете использовать "setInterval", чтобы постоянно проверять, день рождения ли сейчас.
Я использовал базу данных для хранения дней рождения моих пользователей.
В псевдокоде вы должны попробовать следующее:
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
For the most detailed and up-to-date information and guide please visit the Official Birthday Bot Documentation here!
Discord Bot - Celebrate birthdays and anniversaries (NEW) with configurable roles, messages and more! Highly customizable and easy to use! Use bday help to get started!
- Each user can set their birthday & time zone into the bot which stores that information into a database allowing the bot to know on what day and what time zone to celebrate the user's birthday
- Use the Anniversary System to celebrate the anniversary of when members first joined the server and when the server was created.
- Requires the Default Timezone Setting to be set
- Server owners have heavy control over how, when, and what Birthday Bot does in their Discord
- Customization of the Celebration Messages (Message contents and design)
- There can be multiple custom messages, the bot will choose one random for each birthday/anniversary
- Avoid having to vote to use some commands.
- Setup Member Anniversary Roles to celebrate how long members have been in your discord
- For example, the 5-Year Veteran role can be set to be given on a member's 5 Year anniversary in your discord.
- Use the RequireAllTrustedRoles setting to decide if users need all trusted roles or just one to have their birthday celebrated.
- Up to 500 custom birthday messages (vs3for free).
- Up to 500 custom member anniversary messages (vs3for free).
- Up to 500 custom server anniversary messages (vs1for free).
- Decide what color each custom message is (You can have a different color for each!)
- Decide which messages are embedded (Color setting only applies to messages that are embedded)
- One custom message per user
- Unlimited user-specific messages per server
- Since I started Birthday Bot I have maintained development and server cost completely out of my own expense, Birthday Bot Premium allows me to continue to maintain development as Birthday Bot continues to gain tens of thousands of servers each month.
- Subscriptions to Birthday Bot Premium go straight to server costs.
Birthday Bot is a part of the Arilyn Bot family and any support, questions or feedback are welcome in our support Discord. Please visit our FAQ and setup guide, as well as previous user questions before contacting staff, thanks!
Example Birthday Announcement (Fully customizable):
In your Discord server Birthday Bot will track your users' birthdays and using their time zone celebrate their birthday through its customizable birthday role and message. Even if you have a large discord, use Birthday Bots trusted-role system to only celebrate the users you want to avoid the spam of tracking everyone. Similar messages can also be setup to celebrate the anniversary of members joining your discord server and the anniversary of the server itself!
Setting your birthday
Birthday Bot makes everything easy using an easily to follow process.
Start by using bday set .
Birthday Bot uses time zones to detect when to celebrate each user's birthday. If you are unsure of your time zone you can find it here.
Now, you can then reply to this message with your desired time zone.
Birthday Bot will now know your time zone and will use this to know what time to celebrate your birthday!
Now, Birthday Bot will prompt you to put your Birth Month & Date in the following format: MM/DD
Simply reply to this message with your desired date.
Finally, the confirmation menu will appear.
Ensure this is the correct information, then confirm by clicking the checkmark.
Note: Each user only has a limited amount of Birthday Sets. These multiple sets are made to account for incorrect information input, time zone changes, etc. Learn more here.
For users that is it! Server owners will have to do a bit more but Birthday Bot makes it easy with an interactive setup. For more information on server setup follow our guide here.
Finding your time zone
Simply click your location on the map and copy the name of the selected time zone. You can then use it in the bday set command.
For additional help join the support server here.
Birthday Bot does not have a license. This means, while Birthday Bot's code is public to anyone, you do NOT have permission to modify or redistribute this code. Since there is no license, the default copyright laws apply, meaning that I retain all rights to the source code and no one may reproduce, distribute, or create derivative works from it. For more details please visit here.
For the most detailed and up-to-date information and guide please visit the Official Birthday Bot Documentation here!
Discord Bot - Celebrate birthdays and anniversaries (NEW) with configurable roles, messages and more! Highly customizable and easy to use! Use bday help to get started!
- Each user can set their birthday & time zone into the bot which stores that information into a database allowing the bot to know on what day and what time zone to celebrate the user's birthday
- Use the Anniversary System to celebrate the anniversary of when members first joined the server and when the server was created.
- Requires the Default Timezone Setting to be set
- Server owners have heavy control over how, when, and what Birthday Bot does in their Discord
- Customization of the Celebration Messages (Message contents and design)
- There can be multiple custom messages, the bot will choose one random for each birthday/anniversary
- Avoid having to vote to use some commands.
- Setup Member Anniversary Roles to celebrate how long members have been in your discord
- For example, the 5-Year Veteran role can be set to be given on a member's 5 Year anniversary in your discord.
- Use the RequireAllTrustedRoles setting to decide if users need all trusted roles or just one to have their birthday celebrated.
- Up to 500 custom birthday messages (vs3for free).
- Up to 500 custom member anniversary messages (vs3for free).
- Up to 500 custom server anniversary messages (vs1for free).
- Decide what color each custom message is (You can have a different color for each!)
- Decide which messages are embedded (Color setting only applies to messages that are embedded)
- One custom message per user
- Unlimited user-specific messages per server
- Since I started Birthday Bot I have maintained development and server cost completely out of my own expense, Birthday Bot Premium allows me to continue to maintain development as Birthday Bot continues to gain tens of thousands of servers each month.
- Subscriptions to Birthday Bot Premium go straight to server costs.
Birthday Bot is a part of the Arilyn Bot family and any support, questions or feedback are welcome in our support Discord. Please visit our FAQ and setup guide, as well as previous user questions before contacting staff, thanks!
Example Birthday Announcement (Fully customizable):
In your Discord server Birthday Bot will track your users' birthdays and using their time zone celebrate their birthday through its customizable birthday role and message. Even if you have a large discord, use Birthday Bots trusted-role system to only celebrate the users you want to avoid the spam of tracking everyone. Similar messages can also be setup to celebrate the anniversary of members joining your discord server and the anniversary of the server itself!
Setting your birthday
Birthday Bot makes everything easy using an easily to follow process.
Start by using bday set .
Birthday Bot uses time zones to detect when to celebrate each user's birthday. If you are unsure of your time zone you can find it here.
Now, you can then reply to this message with your desired time zone.
Birthday Bot will now know your time zone and will use this to know what time to celebrate your birthday!
Now, Birthday Bot will prompt you to put your Birth Month & Date in the following format: MM/DD
Simply reply to this message with your desired date.
Finally, the confirmation menu will appear.
Ensure this is the correct information, then confirm by clicking the checkmark.
Note: Each user only has a limited amount of Birthday Sets. These multiple sets are made to account for incorrect information input, time zone changes, etc. Learn more here.
For users that is it! Server owners will have to do a bit more but Birthday Bot makes it easy with an interactive setup. For more information on server setup follow our guide here.
Finding your time zone
Simply click your location on the map and copy the name of the selected time zone. You can then use it in the bday set command.
For additional help join the support server here.
Birthday Bot does not have a license. This means, while Birthday Bot's code is public to anyone, you do NOT have permission to modify or redistribute this code. Since there is no license, the default copyright laws apply, meaning that I retain all rights to the source code and no one may reproduce, distribute, or create derivative works from it. For more details please visit here.
Oh, it’s someone’s birthday over the server! How do you get to know if a particular day is someone’s special day? Well, birthdays are dates worth remembering. Wishing people their birthdays and making them feel special has been an old practice of human beings. But what if one wants to remember the birthdays of people they hardly know yet want to make them feel special in any manner. Yes, we here are talking about the scenario over discord. The huge and wide communities over discord are the ones that contain people from all over the world who hardly know each other ever before. It must be noted that these people might share the same interest but they aren’t related to each other in any manner in real lives. Though the world isn’t that a bad place to live in, and people though don’t know each other yet are pleased to wish someone on their birthdays. So, to make this pleasure of greeting people on birthdays much more fun and joyful, the discord community was introduced with an amazing bot that had the ability to make this vision true.
The Birthday bot was thus introduced over discord, owned by Noi and having taken its cover over the major discord servers counting to approximately forty-four thousand servers, the bot has an excellent fanbase among people. The birthday bot serves its users mainly by recognizing birthdays among the user’s community automatically. The bot has an excellent user-friendly and basic interface and is a simple bot that serves for just a single purpose and we all know what. The bot being a single-purpose bot doesn’t offer many features the only one being the assigning of roles for users for the duration of their birthdays. Some of the other features of the bot also include announcing messages for birthdays all over the server. Though such features can be customized and dealt with according to the user’s choice. Another additional and interesting feature that is also a must-needed one for such birthday bots is that the server admins can easily set a particular time zone for the server based on their choice.
TABLE OF CONTENTS
Birthday Bot Command
The default prefix of Birthday Bot is: ‘bday’. Make sure to add this prefix before using the keywords of the commands.
В этой статье я подробно расскажу о том, как работать с библиотекой discord.js, создать своего Discord-бота, а также покажу несколько интересных и полезных команд.
Сразу хочу отметить, что я планирую сделать ряд подобных статей, начиная с простых команд, заканчивая музыкой, системой экономики и распознаванием голоса ботом.
Подготовка к написанию кода
После создания аккаунта для бота, мы должны установить нужные пакеты и модули, чтобы в дальнейшем он корректно работал.
Первым делом создаём папку, после чего открываем её в VS Code (Файл > Открыть папку) / (Ctrl + K Ctrl + O)
Далее нам нужно открыть терминал (Терминал > Создать терминал) / (Ctrl + Shift + `)
Теперь мы должны создать файл с неким «описанием» нашего бота, сделаем это через терминал.
Вписываем данную строку в терминал и нажимаем Enter:
После каждой появившейся строки нажимаем Enter или вписываем свои значения.
Значения в этом файле можно будет изменить в любой момент.Далее, мы должны поочерёдно вводить в терминал эти строки:
«Install» также можно сокращать в «I», но необязательно.
Итого, если вы следовали инструкциям и всё сделали правильно, в вашей папке должны были появиться 3 объекта:
Birthday Bot Discord Benefits and Features
The main aspect of this feature is that the server will now show all the birth dates of the server member based on the particular time zone chosen by the server admin. T hough the developers of the bot visualized that a server might not contain people from a common time zone and thus the bot allows individual members too to set their specified time zone according to their choice. Though the changes made by individual members will reflect only on their side over discord rather than the complete server as in the case of the changes made by the server admin.
Thus, the bot proves out to be an amazing single-purpose bot for carrying out celebrations and wishes over a discord server. It is a much recommended one if it’s not already on your servers, since most of the servers over discord generally have this bot. So do try it out and enjoy discord to the fullest.
Начало работы
Если вы уже знакомы с приведёнными ниже материалами, — смело можете пролистать этот раздел.
Для начала работы с кодом нам нужно установить среду разработки, это может быть:
Среда разработки выбирается по удобству использования и практичности, она у вас может быть любая, но мы рассмотрим её на примере Visual Studio Code, так как она является одной из самых приемлемых для новичков, а также для опытных программистов.
Для установки переходим по этой ссылке.
Выбираем свою операционную систему и запускаем скачивание.Для создания бота мы используем среду выполнения node.js. Для её установки нам необходимо перейти на этот сайт.
На данный момент нас интересует версия долгосрочной поддержки (LTS), скачиваем её.
В Visual Studio Code присутствует возможность устанавливать расширения.
Для этого, кликните по отмеченной ниже иконке.В открывшемся окне вписываем название название/идентификатор нужного нам расширения, после чего устанавливаем его.
Из полезных расширений могу отметить:
-
Discord Presence — расширение, позволяющее отображать рабочую область и файл, в котором вы работаете в вашей игровой активности (функция работает только при использовании приложения Discord).
Читайте также: