Как в дискорде отправить код python
Перейти к содержимому

Как в дискорде отправить код python

  • автор:

Создание Discord-бота на Python. Часть 1

Приветствую, хабровчане и другие пользователи интернета. Сегодня я начну цикл статей, посвящённых созданию Discord-бота с помощью библиотеки discord.py. Мы рассмотрим создание как и примитивного бота, как и "продвинутого" бота с модулями. В этой статье мы сделаем стандартную команду и ещё одну небольшую команду. Начнём!

Создание бота и получение токена

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

Здесь заменяем CLID на ранее скопированный Client ID.

Во вкладке Bot создаём бота и копируем токен.

Написание кода

Устанавливаем саму библиотеку.

Создаём файл config.py (так удобнее), и создаём там словарь.

Создаём main-файл, название может быть любое.
Импортируем библиотеки и наш файл конфига:

Создаём "тело" бота, название может быть любое:

Начинаем писать основной код.

В конце запускаем бота с помощью:

Должно получится так:

Бонусный туториал!

Сделаем вывод случайных картинок с лисами
Для этого импортируем еще пару библиотек:

Приступим к написанию команды.

Должно получится так:

Конец

На этом 1 часть закончена. Скоро будет опубликована 2 часть.

How can I send an embed via my Discord bot, w/python?

I’ve learnt a few stuff,and, now, I’d like to make the things a little more custom.

I’ve been trying to make the bot send embeds, instead, of a common message.

When executing this code, I get the error that ‘Embed’ is not a valid member of the module ‘discord’. All websites, show me this code, and I have no idea of any other way to send a embed.

Tim's user avatar

Norberto A.'s user avatar

6 Answers 6

To get it to work I changed your send_message line to await message.channel.send(embed=embed)

Here is a full example bit of code to show how it all fits:

I used the discord.py docs to help find this. https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.send for the layout of the send method.

Before version 1.0: If you’re using a version before 1.0, use the method await client.send_message(message.channel, embed=embed) instead.

Tim's user avatar

When executing this code, I get the error that ‘Embed’ is not a valid member of the module ‘discord’. All websites, show me this code, and I have no idea of any other way to send a embed.

This means you’re out of date. Use pip to update your version of the library.

Matt's user avatar

Wise Man's user avatar

how about put @client.event instead of the @bot.command() it fixed everything when I put @client.event. @bot.command() does not work you can type

For anyone coming across this in 2022:

how about put @client.event instead of the @bot.command() it fixed everything when I put @client.event. @bot.command() does not work you can type

To this ^, I don’t recommend using @client.event / @bot.event as you’d want to register your commands as a command.

If you want to simply make a command with an embed in your main.py file, make sure you have something like:

However, I personally like separating my commands into a /commands folder and with separate files for all of them as it’s good practice for neater code.

Send an Embed with a Discord Bot in Python

Upgrade your bot's messages and make them a little more custom using embeds!

By Drew Seewald on November 24th, 2020

image

When your Discord bot responds to your server, you don't always want a boring default message to be sent back. Maybe you have links or images that you want to send back in chat. With Python and Discord.py, this is super easy to do in your Discord bot!

Note: This is tested on version 1.4.1 of the Discord.py module. You will encounter issues if you are using a version lower than 1.0. It is recommended that you migrate your code to a more current version.

Building Embeds

Embeds in Discord are simple and have a very clean, formatted look to them. In this tutorial we will go through how to create an embed and customize every part of it.

The embed below is similar to what we will be making. It has a lot going on. There are multiple pictures, links, and text fields that we are able to edit.

You'll know how to make this embed by the end of the tutorial!

You'll know how to make this embed by the end of the tutorial!

Creating the Initial Embed

Title, Description, and color (color is the bar to the left side)

Title, Description, and color (color is the bar to the left side)

When creating an embed, you need to initialize an embed object using the Embed() function from the discord package. We will be using 4 arguments to get started:

title: a string to set the title. This is the first line on our blank embed

url: a string to set the link for the title. When you click on title in the final embed it will take you to this link

description: a string to set the description. This is the darker 2 red lines above

color: a color object. This will color the left edge of the embed.

Let's create a new command in the bot code. Call it embed. All this command will do is build the embed and send it to the channel. In the command build the initial embed object like so:

Start the bot. Go to the server where you joined your bot. Send the embed command we just created. Your bot will return the embed to you!

image

You have multiple options when it comes to colors. You can continue to look up HEX color codes with a tool like Google's Color Picker, or you can use the built in colors inside discord.Color. To use the built in colors, you just use the classmethod of that color's name. To turn the example blue, you would change it like this (change in bold):

Now the embed is blue!Now the embed is blue!

A full list of the color classmethods available for color in Discord.py are available in the documentation.

Adding an Author

image

The author is the text at the very top, and the icon is the circle next to that. Once we have our initial embed object, we can use the .set_author() method on it to add the information for the author. For the author, there are 3 arguments to know:

name: a string with the author's name

url: a string with a link for the author text

icon_URL: a string with the URL location of the picture to use in the author icon

In action, this will look something like this:

Running the bot and using the command in Discord will return the embed with the author information filled in.

image

If you want the author name and icon to be the person who called the command, you can pull that information from the ctx, or context of the command. ctx.author.display_name will pull the username (or nickname if they have one set for the guild) of the person who used the embed command. ctx.author.avatar_url will retrieve the URL of their avatar to use in the embed (changes in bold).

Once the .set_author method is updated, you will see that the icon and author name are updated to match the person who called the embed function.

image

Thumbnails

image

Our next step will be to add the thumbnail. This is the image that goes at the top right of the embed. To add this, we will use the .set_thumbnail() method on our initial embed object. The .set_thumbnail() method takes a single argument that we need to know about:

  • url: a string with the URL location of the picture to use for the embed picture

In action, it will look like this:

Simple as that, our embed now has a thumbnail at the to right.

image

Adding Fields

image

When creating embeds, you have the ability to create a number of text fields with more information. To add these fields, we will use the .add_field() method on our embed object. There are 3 arguments that this method can take that you need to know about:

name: a string with the title of the field

value: a string with the body text of the field

inline: boolean specifying whether the field is inline

Our code will look like this to add a field:

image

Field 1 is not inline, meaning that it will take up the entire line of the embed. If we want to put multiple fields next to each other, we can set inline=True. This will put the next 2 fields we create on the same line. The code will look like this:

And our resulting embed has both fields on the same line.

image

Adding a Footer

image

The final part to customize on our embed is the footer. This is done by using the .set_footer() method on the embed object. This method has only 1 argument, but it is a good place to play around and use information from the ctx variable to enhance it.

  • text: a string with text to display in the footer

A simple footer is added by doing something like this:

image

We can also do some simple string formatting to customize the text with information from ctx. To have it say “Information requested by: subpar”, we can type the sentence with <> as a placeholder for the name variable. Using the .format() string method, we can replace the placeholder with ctx.author.display_name. (Changes in bold)

When we request the embed now, we will see this output:

image

Conclusion

In this post you learned how to create an embed, adding features such as an author, thumbnail, and fields to make it look more interesting. Experiment with the different elements and get your embeds exactly how you like them.

If you are still having trouble creating your own embed, check out the visual embed creator put together by orels1. It has an easy to use interface that allows you to preview your embed and get the code to quickly implement it in your Discord bot.

Run C or Python Programs Using Discord Bot

Abhiram R Pai

During Lockdown I was using discord to interact with my friends while playing video games like among us. We used to play music using discord bot(groovy), while we took a break for like 5 mins. I was constantly thinking about creating a discord bot. I started off with an initial idea of creating a discord bot that would play music. Then one day my friend came up with a wild idea which was running programs written in c or python using a discord bot. I took this up as an challenge and ended up creating a bot that would run c and python program.

Prerequisites

>NodeJs
>CodeEditor (VScode,Atom,Sublime,etc..)
>Discord Account and a Discord Server

Lets Start Creating the bot

First you have to register the bot in discord developer portal .

After you login you will reach this screen then click on new application and you would be able to create a new application.

On this page you can set the bot icon description about the bot etc.

Select bot option, and add a bot.

Now the bot is setup,

Now Lets Code the bot

First lets create a directory for the bot, and also install the dependencies required for coding the bot.

  • discord.js — The Discord library used to create our Discord bot.
  • dotenv — This is going to allow us to hide certain variables, such as our bot’s client ID.
  • request — This package is used to make http and https request.

Lets start coding by opening preferred code editor, I am using vscode.

Now lets add .env and node_modules to .gitignore so that those files are not pushed to github repo in future.

Now we will get the token for our bot from the developer portal,

click on bot option and then click on copy,

Now paste the bot token in .env file

Now in package json add a line inside script tag,

Now lets create a file index.js and add the required dependencies

Now for the compiler we would be using jdoodle api,
sign up and get the client Id and client Secret and paste it in .env file,

Now lets add the code to run c and python program

So lets break the code,

client.on ready is when the discord bot goes online and it would just print coder-BOT is online in the command prompt.

client.on message works when someone sends a message in the channel on which the discord bot has access to.

In our case what we do here is we split the message to check whether the starting of the message contains the pattern “coder”. If a message starts with coder then we understand that the message is to the coderBot. Now here I used switch statement since we have only 1 command the coderbot address that is the run command.

Now when a message comes starting with “coder run” the first case would run and what we do in here is we check what is the argument that comes after the run command if it is c then c compiler is used and if it is python then we use the python interpreter. The index variable is set according to how the index is set in the jdoodle ide i.e, in our case we are using python 3.7.4 which is at index 3 in jdoodle python ide and gcc 5.3.0 c compiler at index 0.

Now after the language is specified we specify the inputs to the file and it is.

Now to capture the file that is uploaded along with the message we use,

Now we send the request using jdoodle api and print the output accordingly.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *