Discord bot token resetting itself

Содержание

The rise of Discord, a chat and voice program favored among gamers, has made it fairly common for Internet denizens to find themselves hanging around “Discord servers” based on a variety of topics. One of the best things about Discord, in fact, is that you can easily make a free server of your own, deck it out with channels, and invite whoever you want to take part in it. After diving into Discord’s neat features, you may be wondering how to make a Discord bot.

(If you’re not well versed on Discord, read our full rundown of what the service is and how it works.)

One of the platform’s coolest features is the ability to create automated users — bots — that can perform various functions. Those bots are coded in JavaScript, and can become rather complex. They do things like play music for users in a server, greeting new users when they arrive, and more.

Creating your own Discord bot doesn’t take much effort, even if you’re new to coding and JavaScript in general. Here’s everything you need to know to make a (super, super simple) Discord bot of your own.

Step 1: Download Node.js and set up a Discord account if you haven’t

Node.js is a JavaScript runtime that’s free and open source, and you’ll need it to actually make your bot, uh, work. Download it at nodejs.org and install it before you get started on anything else.

Obviously, you’ll also need a Discord account, and your own server to use to test your bot. If you haven’t created one yet, go to Discordapp.com and create one. If you do have one, log in to your account and open up the server in which you want your bot to live.

You’ll also need a text editor program, like Notepad++ on Windows, to code with.

Step 2: Create your bot

Now you’ll need to create an “application” on Discord to make your bot work. This takes a little doing, but it’s not too complex. The goal here is to get an “authorization token” for the bot so that Discord recognizes your code and adds it to the bot on its servers.

First, head to discordapp.com/developers/applications/me. Your account should be logged in, so you’ll go straight to your account’s list of applications. Hit New Application
to get started. Give the bot a name, then hit the button marked Save Changes.

Now, on the right-hand menu, click Bot.
Once in the new menu, click Add Bot
 under the Build-a-bot
option. If you only have one application — the one we just made — it should appear automatically. Otherwise, select it.

Step 3: Get your bot’s authorization token

In the box marked App Bot User
, look for the words Token: Click to reveal
. Click that link and you’ll reveal a string of text. That’s your bot’s authorization token, which allows you to send it code. Don’t share it with anyone
— that token allows whoever has it to create code for the bot, which means whoever has it can control your bot. If you think the token has been compromised, the good news is that you can easily generate a new one with the link right under the token, which reads “Generate a new token.”

You’ll need that token in just a second.

Step 4: Send your bot to your server

Now scroll up to the box marked App Details
and find your Client ID
, a long number. Copy the number and add it to this URL, in the place of word CLIENTID.

https://discordapp.com/oauth2/authorize?&client_id=CLIENTID&scope=bot&permissions=8

Copy the URL with your client ID number in it into your browser. That’ll take you to a website where you can tell Discord where to send your bot. You’ll know it worked if you open Discord in an app or in your browser and navigate to your server. The channel will say a bot has joined the room, and you’ll see it on the right side menu under the list of online members.

Step 5: Create a “Bot” folder on your computer

While you’re doing that, you can also take a moment to create a folder in an easy-to-reach place on your computer where you can store all your bot’s files. Call it something simple, like “DiscordBot” or “MyBot” so you know exactly what it is.

Step 6: Open your text editor and make your bot’s files

You’re going to create three files for your bot from your text editor. In the first, paste this code:

Replace “Your Bot Token” with the token you generated earlier on your bot’s application page. Make sure the token is inside the quotation marks. Then save the file into the Discord bot folder you made on your desktop, using the filename “auth.json.” Remember not to save it as a .txt file — it won’t work if it’s .txt instead of .json.

Make a new file, and put in this code:

Replace the author name with your name if you want; you can also change the “description” to something other than “My First Discord Bot” if you want something more in line with what you’re making, which will be handy for remembering what your bot is supposed to do.

Save this file as “package.json” in your Discord bot folder.

Step 7: Define your bot’s code

There’s one more text file to make, and this is the important one that controls your bot’s behavior. You’ll want to be familiar with JavaScript to really have full control of your bot and know what you’re doing, but if you’re new to coding and just want to make something, you can copy and paste this code into the file to make a simple bot that will greet you in your server.

(Thanks to Medium user Renemari Padillo, whose bot tutorial helped us create this one. Check out his tutorial for code troubleshooting and other advice.)

  var Discord = require('discord.io');  var logger = require('winston');  var auth = require('./auth.json');  // Configure logger settings  logger.remove(logger.transports.Console);  logger.add(new logger.transports.Console, {      colorize: true  });  logger.level = 'debug';  // Initialize Discord Bot  var bot = new Discord.Client({     token: auth.token,     autorun: true  });  bot.on('ready', function (evt) {      logger.info('Connected');      logger.info('Logged in as: ');      logger.info(bot.username + ' - (' + bot.id + ')');  });  bot.on('message', function (user, userID, channelID, message, evt) {      // Our bot needs to know if it will execute a command      // It will listen for messages that will start with `!`      if (message.substring(0, 1) == '!') {          var args = message.substring(1).split(' ');          var cmd = args[0];                   args = args.splice(1);          switch(cmd) {              // !ping              case 'ping':                  bot.sendMessage({                      to: channelID,                      message: 'Pong!'                  });              break;              // Just add any case commands if you want to..           }       }  });  

This code sets up a Discord bot that will respond to certain messages: Specifically, anything that starts with a “!” character. In particular, we’re programming the bot to respond to the command “!intro”, so if anyone types that in your server while the bot is in it, the bot will respond with a programmed message. In our code, we defined the message as “Greetings! Welcome to the server!” You can change both the prompt message and the response message by redefining them in the code above. Just make sure to maintain the single quotation marks around the messages.

Save this last text file as “bot.js” in your Discord bot folder.

Step 8: Open your computer’s “Command Prompt” and navigate to your Discord bot folder

On a Windows PC, you can easily get to the Command Prompt by clicking the Windows icon and typing “Command Prompt” in the field. Once it’s open, type “cd” followed by the file path to your folder. On my computer, the command looks like this: “cdUsersPhil’s DesktopDesktopDiscordBot”. That should change the command prompt line to include the file path to your folder.

Alternatively, you can navigate to your folder in Windows and hold Shift while right-clicking on a blank area of the folder, and choosing Open Command Prompt.

Step 9: Use the Command Prompt to install your bot’s dependencies

Now it’s time to make use of Node.js. In the Command Prompt, with your Discord bot folder in the file path line, type “npm install discord.io winston –save.” This will automatically install files you need to for your Discord bot into the folder directly.

Also use the following command line prompt to install additional dependencies: npm install https://github.com/woor/discord.io/tarball/gateway_v6

That should provide you with all the files you need.

Step 10: Run the bot

That should be everything. To try running your bot, type “node bot.js” in the Command Prompt (make sure you’re still navigated to your Discord bot folder).

Now head back to your Discord server and try testing your bot by typing “!intro,” or “!” followed by whatever you made your prompt message in your “bot.js” file. If everything went correctly, your bot should immediately return the message you coded for it.

Congrats! You just made a Discord bot!

Step 11: Figure out if your bot has been made by someone else

Discord has a big community of people making stuff for the greater good of the service all the time, and that includes bots. There are whole databases of bots other people have made that perform a variety of functions, and often their creators make those bots available for anyone to download and use. Save yourself some time and some coding by checking out some of the usual places where Discord bots are found, to see if someone has already done your work for you.

Some handy places to search for Discord bots are discordbots.org and bots.discord.pw, but you’re also likely to have luck googling for what you need, as well.

Editors’ Recommendations

In this tutorial, I’ll create a simple Discord bot using Node.js. The bot will be connected to a Discord server and translate every message that’s not written in English.

Flavio Copes
Follow

Oct 1, 2018 · 6 min read


Discord, the popular chat application for gamers

If you don’t know Discord, it’s one of the most popular chat applications among gamers and has attracted non-gaming communities as well.

Communities are called Servers. Each time you create a new one, you create a server, give it a name, and create several channels. In the programming world, I can mention Nodeiflux, Reactiflux, SpeakJS, Vue Land, and the /r/webdev
server.

There are many more, of course, those can get you started if you don’t know any community to join.

But let’s get to the meat of the article. Say I just created a server, and before inviting my friends to join and discuss what’s the best JS framework (might not end well), I want to create a bot
that will translate every word added to the channel that is not in English
.

Tip: Use Bit
to reuse components and build faster! Easily organize and use your components to build multiple apps with your team. Give it a try.

Component Discovery and Collaboration · Bit

Bit is where developers share components and collaborate to build amazing software together. Discover components shared…

bit.dev

React spinners with Bit: Choose, Play, Use

Discord provides a great documentation for developers at
https://discordapp.com/developers/docs/intro
. Make sure you check it out!

First login to https://discordapp.com and create an account if you haven’t one already.

Then head to https://discordapp.com/developers/applications/ to create the bot application:

Click the “Create an application” button. In the next screen, give the app a name:

I’m going to call mine “English as a service”.

Scroll a little and you’ll find the client id
, a number that identifies your application.

Save it somewhere safe, we’ll use it soon.

Now click the “Bot” menu in the left sidebar, and press “Add Bot”:

Doing this will give life to our bot.

The important thing that happens here is that Discord gives the bot token
.

We’ll need to use this in the Node.js bot code.

Before going to the code, however, let’s add the bot to the server. First, for the sake of testing, create a test server. We’ll put our bot into it.

From the Discord application, in the sidebar press the +
button:

and click “Create a Server”. I called mine “Testing the bot”.

Now copy/paste this link to add the bot to your server:

https://discordapp.com/oauth2/authorize?&client_id=ENTER_YOUR_BOT_CLIENT_ID_HERE&scope=bot&permissions=8

Make sure you fill the client id you saw before in this URL.

You’ll see this screen, uncheck “Administrator” and authorize:

You should see the bot joined your server!

It’s finally time to code! 🙌🏼

I’ll be using Glitch in this example. Glitch is a great service for this kind of thing — you can easily create applications, and they will run directly from Glitch — there are some fair use limitations, but for a simple bot it will be more than enough.

Create an account on Glitch, then hit this url https://glitch.com/edit/#!/remix/hello-node-server to start a brand new Node.js application.

We’ll use the discord.js
library to create our bot. Using a library makes all very easy since the tiny details are abstracted for us.

The app offers a great guide and a nicely organized API documentation.

To import it in Glitch, open the package.json
file, and click “Add Package”.

Just click the library to install it using npm
.

Now open the .env
file. This file is the way that Glitch offers us to handle secret tokens. Every app is publicly readable by default (you can make it private) but no one can read this file content, which makes sharing an application code quite safe.

Add those lines in there:

We log in to Discord using the bot:

client.login(process.env.BOT_TOKEN)

and we create the simplest bot that we can possibly make. Every time a user says “ping”, the bot responds with “pong”:

client.login(process.env.BOT_TOKEN)

We can now focus on what the bot must actually do.

It will listen for every message, ask for the translation to a service that provides them (we’ll use the Yandex Translations API) and if the answer is different from the words entered it means the original language was not English, and we can write the answer back.

Go to https://tech.yandex.com/translate/. If you don’t have a Yandex account, create one for free.

Then create an API key from the interface:

According to the Terms of Use for the Yandex.Translate service, the text “Powered by Yandex.Translate” must be shown above or below the translation result, with a clickable link to the page
http://translate.yandex.com/
. As this is just a private sample application, I won’t do it, but be aware of this.

Now, store this API key in the .env
file as YANDEX_API_KEY
.

The Yandex Translate API documentation (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/) tells us to build an API request in this way:

The lang
in the query parameter can take the form -
or just
(in this case “from” will be guessed from the message). For example en
or it-en
.

In our case, we’ll just guess the origin language, and we’ll use en
as this parameter value.

Using Axios (in Glitch, search for axios
in the package.json
“Add package”) we’ll perform a network request to the Yandex Translate API.

See
https://flaviocopes.com/axios
to get an intro to Axios

We pass in the params
object, and we listen for the promise to complete in the then()
callback:

const axios = require('axios')
//...

What are we doing here? First, we listen for messages from the chat, as we did before with ping/pong.

This time, however, we pass all messages through the Yandex Translate API, asking to translate to English if we get back a string different than the one we sent, it means the original language was not English, and we reply to the person with the translation (in this way the translation is linked to the original message).

Here’s an example of the bot in action:

So, to wrap up, we created a Discord bot and used the Yandex Translate API to provide a translation service for our Discord server. Our bot was developed on Glitch, and it’s automatically deployed there for free.

You can find the source code of the sample bot at https://glitch.com/edit/#!/discord-bot-translate?path=server.js

I hope this little introduction to Discord bots will help you create yours!

5 Tools For Faster Development In React

5 tools to speed the development of your React application, focusing on components.

blog.bitsrc.io

Building a UI Component Design System

Learn how Uber, Pinterest, Shopify and Airbnb are leveraging components to build a consistent UI/UX design system.

blog.bitsrc.io

How To Write Better Code In React

9 Useful tips for writing better code in React: Learn about Linting, propTypes, PureComponent and more.

blog.bitsrc.io

Асинхронная библиотека discord.py содержит все что нужно для бота, с помощью нее даже можно работать с голосовыми каналами сервера. В этой статье я расскажу как создать простенького бота для вашего discord сервера.

Получение токена и Client ID для вашего бота

Для получения токена и ID бота небходимо создать свое приложение и в разделе General Information скопировать Client ID. А в разделе настроек создать бота и скопировать его токен. Задача не сложная, думаю все с этим справятся.

Собственно пишем бота

Устанавливаем discord.py с помощью pip:

pip install discord

После успешной установки создаем файл bot.py, где будем писать бота. Импортируем все необходимое:

import discord from discord.ext import commands 

Создаем переменную с вашим токеном, про который я писал выше:

TOKEN = 'Ваш токен'
Про токен

Создаем тело бота:

bot = commands.Bot(command_prefix='!') #инициализируем бота с префиксом '!'

Для начала сделаем простенькую команду, аргумент которой бот будет просто пересылать:

 @bot.command(pass_context=True) #разрешаем передавать агрументы async def test(ctx, arg): #создаем асинхронную фунцию бота     await ctx.send(arg) #отправляем обратно аргумент 

И в конце запускаем бота с вашим токеном:

bot.run(TOKEN)

В итоге должно получится вот такое:

Код
 import discord from discord.ext import commands  TOKEN = 'Ваш токен' bot = commands.Bot(command_prefix='!')   @bot.command(pass_context=True)  # разрешаем передавать агрументы async def test(ctx, arg):  # создаем асинхронную фунцию бота     await ctx.send(arg)  # отправляем обратно аргумент   bot.run(TOKEN)  

Теперь необходимо добавить бота на сервер. Сделать это можно с помощью ссылки:

https://discordapp.com/oauth2/authorize?&client_id={Client ID}&scope=bot&permissions={Права, например 66395456}

Число необходимых прав можно получить в разделе настроек бота. Теперь можно запускать бота:

python bot.py

После нескольких секунд, можно заметить его в сети: И наконец-то попробовать отправить команду:

Заключение

Вот так можно легко запустить у себя на сервере бота. Как можно заметить библиотека делает практически все за тебя и остается только добавлять свой функционал с использованием python. В следующий раз я покажу как следить за событиями, подключатся к голосовым каналам (избегая проблем с linux и Windows), использовать роли и права участников и другое. Надеюсь, статья была Вам полезна, удачи!

Рейтинг автора
5
Подборку подготовил
Андрей Ульянов
Наш эксперт
Написано статей
168
Ссылка на основную публикацию
Похожие публикации