mkdir MyDiscordLogger
cd MyDiscordLogger
dotnet new console
dotnet add package Discord.Net --version 3.9.0
3) Store your token
For safety, don’t hard-code your token in source. On Windows PowerShell:
ps1
$Env:DISCORD_TOKEN = "YOUR_BOT_TOKEN_HERE"
Or on Linux/macOS:
bash
export DISCORD_TOKEN="YOUR_BOT_TOKEN_HERE"
4) Program.cs
Replace the contents of Program.cs with:
csharp
using System;
using System.IO;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
namespace MyDiscordLogger
{
class Program
{
// The Discord client
private readonly DiscordSocketClient _client;
// Path to your log file
private const string LogPath = "messages.txt";
static async Task Main(string[] args)
=> await new Program().MainAsync();
public Program()
{
// You can tweak GatewayIntents if you only need certain events:
var config = new DiscordSocketConfig
{
// This intent is required to receive message content:
GatewayIntents = GatewayIntents.Guilds
| GatewayIntents.GuildMessages
| GatewayIntents.DirectMessages
| GatewayIntents.MessageContent
};
_client = new DiscordSocketClient(config);
// Hook the event
_client.MessageReceived += MessageReceivedAsync;
_client.Log += LogAsync;
}
public async Task MainAsync()
{
// Grab token from environment variable
var token = Environment.GetEnvironmentVariable("DISCORD_TOKEN");
if (string.IsNullOrWhiteSpace(token))
{
Console.WriteLine("Please set DISCORD_TOKEN as an environment variable.");
return;
}
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
Console.WriteLine("Bot is running. Press CTRL+C to exit.");
// Block this task until the program is closed.
await Task.Delay(-1);
}
private Task LogAsync(LogMessage log)
{
Console.WriteLine(log.ToString());
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(SocketMessage message)
{
// ignore system messages or messages from bots (including ourselves)
if (message.Source != MessageSource.User)
return;
var timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
var channelName = (message.Channel is ITextChannel tc)
? $"{tc.Guild.Name}/{tc.Name}"
: message.Channel.Name;
var author = $"{message.Author.Username}#{message.Author.Discriminator}";
var content = message.Content.Replace("\r\n", "\\n");
var logLine = $"{timeStamp} | #{channelName} | {author}: {content}{Environment.NewLine}";
// Append to file asynchronously
await File.AppendAllTextAsync(LogPath, logLine);
}
}
}
5) Run the bot
bash
dotnet run
→ The bot will come online (you should invite it to at least one server with the “Read Messages” intent). Every incoming message will be appended to messages.txt in your project folder.
Tips & Extensions
Thread‐safe logging: for very high traffic, consider StreamWriter with a shared lock or a logging queue.
Filters: skip logging images/embeds or attachments if you like.
Formatting: you can switch to JSON‐based logs for easier parsing.