编程语言
首页 > 编程语言> > 简单用python写一个discord机器人

简单用python写一个discord机器人

作者:互联网

前提

说了很久换鼠标还是没换,没钱呐ლ(′◉❥◉`ლ)

正文

先新建一个.py文件
然后呢,win+r打开cmd
输入pin install discord.py

在新建的文件里输入:

import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('你是憨批吗?'):
        await message.channel.send('不是')

client.run('刚刚复制的token')

现在,一个基本的bot已经搭好了
在(.py 文件的)目录里按shift+右键
用powershell打开

输入python 文件名.py
然后会看到We have logged in as 天哥der私人BOT#0164之类的文件

然后打开https://discord.com/developers
新建一个机器人
打开oauth2,勾选bot
用浏览器打开链接,把bot添加到你的群里

为bot添加点功能

刚刚已经写(?)好了基本的回复功能
接下来我们会帮机器人添加进群欢迎和退出提醒
在代码后面(token前面)添加以下代码:

#欢迎消息
async def on_member_join(member):
    print(F"{menber} was join")
    await message.channel.send(F"欢迎 {menber} ━(*`∀´*)ノ亻!")

async def on_member_remove(member):
    print(F"{menber} was remove")
    await message.channel.send(F"不讲武德der {menber} 退出了,我劝你耗子尾汁")

最后,代码会是这样子的:

import discord
from discord.ext import commands

client = discord.Client()
bot = discord.ext.commands.Bot(command_prefix = "your_prefix");

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

#自动回复?
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith("!test"):
        await message.channel.send("the bot was running!")

@bot.event
async def on_ready():
    print(">>bot was online<<")

#欢迎消息
async def on_member_join(member):
    print(F"{menber} was join")
    await message.channel.send(F"欢迎 {menber} ━(*`∀´*)ノ亻!")

async def on_member_remove(member):
    print(F"{menber} was remove")
    await message.channel.send(F"不讲武德der {menber} 退出了,我劝你耗子尾汁")

client.run("ODQyODg4MzYxODA2Mzk3NDUx.YJ729Q.3XkzVaJSa9VYPYOyDNVjqTO1lXs")

标签:discord,python,机器人,bot,client,async,message,def
来源: https://www.cnblogs.com/MCTG/p/14770748.html