[译] 如何用 Python 写一个 Discord 机器人
- 原文地址:How to write a Discord bot in Python
- 原文作者:Junpei Shimotsu
- 译文出自:掘金翻译计划
- 本文永久链接:github.com/xitu/gold-m…
- 译者:Starrier
- 校对者:mrcangye、IllllllIIl
如何用 Python 写一个 Discord 机器人
在本教程中,您将学习如何使用 Python 创建一个简单的 Discord 机器人。 也许您还不知道什么是 Discord,本质上它是一项针对游戏玩家的一种类 Slack(一个云协作团队工具和服务)的服务。
在 Discord 上,您可以连接多个服务器,您一定也注意到这些服务器有许多机器人。 这些机器人可以做很多事情,从为您播放音乐到简单的聊天。 我被这些机器人深深吸引,因此决定用 Python 写一个属于自己的机器人。 那么让我们立刻开始吧!
设置
我们首先要创建一个机器人账号。 转到 discordapp.com/developers/… 然后创建一个新的 app。 给您的机器人起一个好听的名字,并给它配上一张个人资料图片。
向下滚动并点击"Create Bot User"。 完成后您将得到一个机器人的私密 token。
您也可以点击以显示机器人的 toke。
永远不要和任何人分享您的 token,因为他们可能会以此来挟持您的机器人。 在写完这篇文章后,我会更换 token。
代码
现在,开始享受吧。
准备环境
- Python 3
- pip
Discord.py (重写)
现在我们要安装 discord.py 库的重写版本。 pip 上的 discord.py 没有得到积极维护,因此请安装库的重写版本。
$ python3 -m pip install -U https://github.com/Rapptz/discord.py/archive/rewrite.zip
检查您正在使用的 discord.py 版本,
>>> import discord
>>> discord.__version__
'1.0.0a'
一切已经准备就绪,让我们开始写机器人吧。
import discord
from discord.ext import commands
如果它报 ModuleNotFoundError
或者 ImportError
那么您的 discord.py 安装有问题。
bot = commands.Bot(command_prefix='$', description='A bot that greets the user back.')
命令前缀是消息内容最初调用命令所必须包含的内容。
@bot.event
async def on_ready():print('Logged in as')print(bot.user.name)print(bot.user.id)print('------')
当客户端准备好从 Discord 中接收数据时,就会调用 on_ready()
。 通常是在机器人成功登录后。
现在让我们为机器人添加一些功能。
@bot.command()
async def add(ctx, a: int, b: int):await ctx.send(a+b)@bot.command()
async def multiply(ctx, a: int, b: int):await ctx.send(a*b)@bot.command()
async def greet(ctx):await ctx.send(":smiley: :wave: Hello, there!")@bot.cmmands()
async def cat(ctx):await ctx.send("https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif")
在运行它之前,必须将您的机器人添加到您的服务器。 这个 OAuth2 url 可以从您的机器人 settings 页面生成。 转到 https://discordapp.com/developers,点击您的机器人配置文件并生成 oAuth2 url。
这是您决定给机器人授予什么权限的地方。 对于我们现在的使用情况,我们只需要赋予发送消息的权限即可。
现在,让我们在命令行中运行以下命令来启动机器人。
$ python bot.py
现在我们开始测试机器人。
在创建一个 Discord 机器人时,应该遵循一系列优秀的实践。 我建议您在这里 github.com/meew0/disco… 阅读整个文档。
有个信息命令。 它应该提供关于机器人的信息,比如它使用的框架,框架用的是哪个版本以及帮助命令,最重要的一点是,它的开发者是谁。
@bot.command()
async def info(ctx):embed = discord.Embed(title="nice bot", description="Nicest bot there is ever.", color=0xeee657)# 在这里提供关于您的信息embed.add_field(name="Author", value="<YOUR-USERNAME>")# 显示机器人所服务的数量。embed.add_field(name="Server count", value=f"{len(bot.guilds)}")# 给用户提供一个链接来请求机器人接入他们的服务器embed.add_field(name="Invite", value="[Invite link](<insert your OAuth invitation link here>)")await ctx.send(embed=embed)
discord.py 会自动生成一个 help
命令。 所以要自定义时,我们首先要删除默认提供的。
bot.remove_command('help')
现在我们可以编写自定义的 help
命令了。请在这里描述您的机器人。
@bot.command()
async def help(ctx):embed = discord.Embed(title="nice bot", description="A Very Nice bot. List of commands are:", color=0xeee657)embed.add_field(name="$add X Y", value="Gives the addition of **X** and **Y**", inline=False)embed.add_field(name="$multiply X Y", value="Gives the multiplication of **X** and **Y**", inline=False)embed.add_field(name="$greet", value="Gives a nice greet message", inline=False)embed.add_field(name="$cat", value="Gives a cute cat gif to lighten up the mood.", inline=False)embed.add_field(name="$info", value="Gives a little info about the bot", inline=False)embed.add_field(name="$help", value="Gives this message", inline=False)await ctx.send(embed=embed)
恭喜!您刚刚用 Python 创建了一个 Discord 机器人。
托管
目前,机器人只会在您运行脚本之前在线运行。 因此,如果您希望您的机器人一直运行,您必须在线托管它,或者您也可以在本地托管它。比如在树莓派(RaspberryPi)。 托管服务范围很广,从免费的(Heroku's free tier)到付费的(Digital Ocean)。 我在 Heroku's free tier 上运行我的机器人,到目前为止还没有遇到任何问题。
源代码
import discord
from discord.ext import commandsbot = commands.Bot(command_prefix='$')@bot.event
async def on_ready():print('Logged in as')print(bot.user.name)print(bot.user.id)print('------')@bot.command()
async def add(ctx, a: int, b: int):await ctx.send(a+b)@bot.command()
async def multiply(ctx, a: int, b: int):await ctx.send(a*b)@bot.command()
async def greet(ctx):await ctx.send(":smiley: :wave: Hello, there!")@bot.command()
async def cat(ctx):await ctx.send("https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif")@bot.command()
async def info(ctx):embed = discord.Embed(title="nice bot", description="Nicest bot there is ever.", color=0xeee657)# give info about you hereembed.add_field(name="Author", value="<YOUR-USERNAME>")# Shows the number of servers the bot is member of.embed.add_field(name="Server count", value=f"{len(bot.guilds)}")# give users a link to invite thsi bot to their serverembed.add_field(name="Invite", value="[Invite link](<insert your OAuth invitation link here>)")await ctx.send(embed=embed)bot.remove_command('help')@bot.command()
async def help(ctx):embed = discord.Embed(title="nice bot", description="A Very Nice bot. List of commands are:", color=0xeee657)embed.add_field(name="$add X Y", value="Gives the addition of **X** and **Y**", inline=False)embed.add_field(name="$multiply X Y", value="Gives the multiplication of **X** and **Y**", inline=False)embed.add_field(name="$greet", value="Gives a nice greet message", inline=False)embed.add_field(name="$cat", value="Gives a cute cat gif to lighten up the mood.", inline=False)embed.add_field(name="$info", value="Gives a little info about the bot", inline=False)embed.add_field(name="$help", value="Gives this message", inline=False)await ctx.send(embed=embed)bot.run('NDE0MzIyMDQ1MzA0OTYzMDcy.DWl2qw.nTxSDf9wIcf42te4uSCMuk2VDa0')
掘金翻译计划 是一个翻译优质互联网技术文章的社区,文章来源为 掘金 上的英文分享文章。内容覆盖 Android、iOS、前端、后端、区块链、产品、设计、人工智能等领域,想要查看更多优质译文请持续关注 掘金翻译计划、官方微博、知乎专栏。
[译] 如何用 Python 写一个 Discord 机器人相关推荐
- 贪吃蛇博弈算法python_算法应用实践:如何用Python写一个贪吃蛇AI
原标题:算法应用实践:如何用Python写一个贪吃蛇AI 前言 这两天在网上看到一张让人涨姿势的图片,图片中展示的是贪吃蛇游戏, 估计大部分人都玩过.但如果仅仅是贪吃蛇游戏,那么它就没有什么让人涨姿势 ...
- 手机版python3h如何自制游戏_教你如何用 Python 写一个小游戏
教你如何用 Python 写一个小游戏 引言 最近 python 语言大火, 除了在科学计算领域 python 有用武之地之外, 在游戏后台等方面, python 也大放异彩, 本篇博文将按照正规的项 ...
- python爬虫抢火车票_如何用python写一个简单的12306抢票软件|python 爬火车票 教程...
python 如果抓取验证码图片 类似12306的登录验证码图片 这个以前做次.最大的麻烦是码的识别算法的识别率太低.12306那种网站登陆错3次就限制你20分钟.所以除非你有33%以上的识别率否则不 ...
- 如何用python写一个计算日期间隔的程序?
如何用python写一个计算日期间隔的程序? 文章目录 如何用python写一个计算日期间隔的程序? 前言 问题梳理 问题解决 写在后面 前言 为什么想起来写一个这样的程序呢? 前几天聊天的时候,突然 ...
- python 题库自动答题,自动匹配题库_如何用python写一个从题库自动匹配的答题脚本_淘题吧...
A. web数据库题目:根据用户输入的用户名和密码于数据库中的记录是否匹配制作一个用户登录模块 http://blog.csdn.net/love_leve/article/details/43226 ...
- python能制作游戏吗_如何用python写一个小游戏
广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 引言最近python语言大火,除了在科学计算领域python有用武之地之外,在游 ...
- python解析器是什么_如何用python写一个简单的词法分析器
编译原理老师要求写一个java的词法分析器,想了想决定用python写一个. 目标 能识别出变量,数字,运算符,界符和关键字,用excel表打印出来. 有了目标,想想要怎么实现词法分析器. 1.先进行 ...
- python写词法分析器_如何用python写一个简单的词法分析器
编译原理老师要求写一个java的词法分析器,想了想决定用python写一个. 目标 能识别出变量,数字,运算符,界符和关键字,用excel表打印出来. 有了目标,想想要怎么实现词法分析器. 1.先进行 ...
- 如何用Java写一个聊天机器人
文章目录 建议结合新版教程看 写在前面的的话 免责声明 你需要提前会的东西 我们要使用的框架 首先我们先下载一个Demo 文件配置 Demo里面的的目录结构 在配置文件中加上你小号的QQ名字和密码 我 ...
最新文章
- JavaScript原生代码处理JSON的一些高频次方法合集
- ASP.NET MVC Framework 系列
- Python多线程和队列结合demo
- (转)响应式Web设计是大势所趋还是时代的产物
- P2668 斗地主 dp+深搜版
- Gensim Word2vec 使用教程
- CentOS 7.4 下 如何部署 AspNetCore 结合 consul
- FusionCharts 技术文档-Jsp画图例子
- Bootloader之BareBox 之路(1)--安装
- jeecg框架MybatisPlus出现查询条件重复现象
- excel表格自动添加边框
- js中apply、bind、call的用法和区别
- [ZGC升级记录](to-space exhausted/Evacuation Failure)
- 机器学习实战(Machine Learning in Action)学习笔记————09.利用PCA简化数据
- Maxima绘图基础
- 四级常见英语短语1000条
- 爬取豆瓣电影排行榜,并制作柱状图与3d柱状图
- Bloc入门之Cubit详解
- yolov5 detect文件参数解释(部分)
- HAL库中断方式实现串口通信操作
热门文章
- 使用php-amqplib连接rabbitMQ 学习笔记及总结
- python宽度优先搜索算法并输出路径
- Weblogic ./startWebLogic.sh Error 解决
- Head First Design Pattern 读书笔记(4) 工厂模式
- html表单用户名,HTML表单
- cocos2dx游戏开发简单入门视频教程 (cocos2d-x)- 第5天
- 算法列表-java实现
- 输入用户名和密码登入到服务器,却显示指定的网络密码不正确,输入了好几次都是这样,这是怎么回事? 用户名和密码没问题 ,一直用的好好地今天就不行了...
- 电脑办公技巧:他做了9小时的工作,我5秒就做完了
- 如何在《救赎之路》中使用CPU粒子效果