【问题标题】:DISCORD.PY PYTHON - I want to make a function which sends a global message in the server when a user joins in the serverDISCORD.PY PYTHON - 我想创建一个函数,当用户加入服务器时在服务器中发送全局消息
【发布时间】:2020-01-10 12:18:30
【问题描述】:

我正在尝试使用 Python 制作 Discord BOT。我正在创建不同类型的函数,现在我想创建一个函数,让 BOT 在有人加入服务器时在通用频道中发送消息

import discord
import random

from discord.ext import commands

token = 'BOT_TOKEN'
client = commands.Bot(command_prefix = '!')

@client.event
async def on_ready():
    print(f'{client.user.name} is now ready')

@client.command(aliases = ['ask', 'chiedi'])
async def _ask(ctx, *, question):
    file_object = open("quotes.txt")
    quotes = file_object.readlines()
    file_object.close()

    rnd = random.choice(quotes)
    await ctx.send(rnd)

@client.event
async def on_message(message):
    author = message.author
    content = message.content
    log = '{}: {}'.format(author, content)
    with open("logs.txt", "a+") as my_file:
        my_file.write(log + "\n")
        my_file.close()

'''
func print_msg
    once the user joins the server
    print message to greet him

'''

client.run(token)

我希望输出类似于“用户名已加入我们的服务器!欢迎。”

【问题讨论】:

  • 请更具体一些,并提供您完成的工作的代码 sn-ps 以便确定问题范围。
  • 我编辑了你的帖子; 不要向任何人展示您的机器人令牌。拥有您的机器人令牌的人可以访问您的整个机器人。
  • 我知道,这是一个不同的令牌

标签: python discord discord.py pypi


【解决方案1】:

假设您使用的是版本1.3.0a...(或接近的地方)

您基本上可以按照他们在here 上提供的模板进行操作。 on_ready() 有一个,on_message(message) 有另一个。
只需在文档中找到您需要的相应事件,您可能想要的是 on_member_join(member)
像这样:

# ...
@client.event
async def on_member_join(member):
    await member.guild.text_channels[0].send("A message sent to the first channel because a member joined!")
# ...

【讨论】:

  • /Python Bot/domenico.py:35: RuntimeWarning: coroutine 'Messageable.send' is never waiting member.guild.text_channels[0].send("Test") RuntimeWarning: E​​nable tracemalloc to get对象分配回溯
  • @LorenzoOrlando 我忘记在后面添加await... 编辑了我的答案;
  • 谢谢先生!现在它正在工作。但是,如果有人离开或被踢时我想做同样的事情怎么办?我应该把它改成 on_member_leave 吗?
  • @LorenzoOrlando 事件及其描述和接口在Event Reference中描述
猜你喜欢
  • 2021-01-09
  • 2018-07-27
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 2023-02-10
  • 1970-01-01
  • 2021-11-12
  • 2020-01-22
相关资源
最近更新 更多