简体   繁体   中英

How send a message with a Discord Bot in C#?

I'm trying to understand how should I send a message with Discord Bot into my channel without any event or command sent by me?

The result that I would like to achieve is that through a timer bot you send a message in the chat every minute.

If you can explain it to me with some examples, I would be very grateful to you

There are various ways to send messages into channels without using commands. In essence, you are asking how to send messages from a class that does not inherit from ModuleBase .

This requires you to use Dependency Injection to inject your DiscordSocketClient into the class you want to send messages from.

You can learn more about Dependency Injection (because it is a large topic) in the official documentation and in the example bot provided by Discord.Net (assuming you are using this library).

The simple solution is shown below.

public class MyClass
{
    private readonly DiscordSocketClient _client;
    public MyClass(DiscordSocketClient client) => client = client 

    public async Task SendMessageToChannel(ulong channelId, string message)
    {
        SocketChannel channel = _client.GetChannel(channelId);
        await (channel as IMessageChannel).SendMessageAsync(message);
    }
} 

Ideally you should also create an interface called IMyClass and have MyClass implement it. This way, you can effectively configure the methods of MyClass as a service too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM