📅  最后修改于: 2023-12-03 15:14:41.443000             🧑  作者: Mango
In this tutorial, we will create a Discord Bot in C# that will display the current time in a specific timezone. We will be using the Discord.Net library to handle interactions with the Discord API, and the TimeZoneInfo class from the System library to get the current time in the specified timezone.
To follow this tutorial, you will need:
First, we need to create a Discord Bot and add it to our server. To do this, follow these steps:
Create a new C# Console Application project in Visual Studio. Then, add the Discord.Net and Newtonsoft.Json libraries to your project using NuGet packages.
using Discord;
using Discord.Commands;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Web;
In the Program.cs file, we can write the following code:
class Program
{
static void Main(string[] args) => new Program().MainAsync().GetAwaiter().GetResult();
private DiscordSocketClient _client;
private CommandService _commands;
public async Task MainAsync()
{
// Create a new Discord Client
_client = new DiscordSocketClient();
// Create a new Command Service
_commands = new CommandService();
// Register the Command Service to the Discord Client
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), null);
// Add Event Handlers to the Discord Client
_client.MessageReceived += HandleCommandAsync;
// Login to the Discord Bot
await _client.LoginAsync(TokenType.Bot, "YOUR BOT TOKEN");
// Start the Discord Bot
await _client.StartAsync();
// Wait for the bot to stay running
await Task.Delay(-1);
}
private async Task HandleCommandAsync(SocketMessage messageParam)
{
// Ignore system messages
var message = messageParam as SocketUserMessage;
if (message == null) return;
// Check if message starts with 'time'
if (!message.Content.ToLower().StartsWith("time")) return;
// Get command arguments
var arg = message.Content.Substring(4);
// Get the TimeZoneInfo of the specified timezone
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(arg);
// Get the current time in the specified timezone
var time = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZoneInfo);
// Send the current time in the specified timezone to the Discord channel
await message.Channel.SendMessageAsync($"The current time in {arg} is {time.ToString("hh:mm tt")}.");
}
}
Build and run your project to start the bot.
In this tutorial, we have created a Discord Bot in C# that displays the current time in a specific timezone. You can further customize this bot to suit your needs by adding more commands or integrating it with other APIs.