簡體   English   中英

Discord.py 發送消息到特定通道

[英]Discord.py send message to specific channel

無論在哪個服務器上,我都想在特定的文本頻道中發送消息,因此我無法硬編碼我的頻道 ID。

這部分代碼正在工作:

    @client.event
async def on_guild_join(guild):
    general = find(lambda x: x.name == 'general',  guild.text_channels)
    if general and general.permissions_for(guild.me).send_messages:
        await general.send('Hello {}!'.format(guild.name))

但我的問題是這部分女巫在齒輪中:

import discord, httplib2, random, string
from discord.ext import commands
from datetime import datetime
from discord.ext.commands import cooldown
from discord.utils import find
class Cog01(commands.Cog):

    def __int__(self, client):
        self.client = client



    @commands.Cog.listener()
    async def on_ready(self):
        print('Cog01 is loaded')

        fff = find(lambda x: x.name == 'general',  guild.text_channels)


def setup(client):
    client.add_cog(Cog01(client))

我收到了這個錯誤:

NameError: name 'guild' is not defined

我嘗試了很多東西,有時錯誤消失了,但仍然沒有用。

我確信這是可能的,我丟失了一個有效的舊版本代碼。

我一直在尋找解決方案幾個小時,但解決方案可能非常簡單,我是編程新手。

commands.Bot有一個guilds屬性,該屬性返回客戶端連接到的每個公會的列表。
那么每個Guild object 都有一個system_channel屬性。 這是在此頻道上發送用戶已加入之類的消息。

例如,如果您想在機器人准備就緒時在這些頻道上發送消息,您可以這樣做:

from discord.ext import commands

class Cog01(commands.Cog):
    def __int__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        for guild in self.client.guilds:
            await guild.system_channel.send("I'm ready to go!")

def setup(client):
    client.add_cog(Cog01(client))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM