Add sample bots to the solution (#972)
* Add sample bots to the solution * Fix missing attributes, show use of preconditions
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
|
||||
namespace _02_commands_framework.Services
|
||||
{
|
||||
public class CommandHandlingService
|
||||
{
|
||||
private readonly CommandService _commands;
|
||||
private readonly DiscordSocketClient _discord;
|
||||
private readonly IServiceProvider _services;
|
||||
|
||||
public CommandHandlingService(IServiceProvider services)
|
||||
{
|
||||
_commands = services.GetRequiredService<CommandService>();
|
||||
_discord = services.GetRequiredService<DiscordSocketClient>();
|
||||
_services = services;
|
||||
|
||||
_discord.MessageReceived += MessageReceivedAsync;
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
|
||||
}
|
||||
|
||||
public async Task MessageReceivedAsync(SocketMessage rawMessage)
|
||||
{
|
||||
// Ignore system messages, or messages from other bots
|
||||
if (!(rawMessage is SocketUserMessage message)) return;
|
||||
if (message.Source != MessageSource.User) return;
|
||||
|
||||
// This value holds the offset where the prefix ends
|
||||
var argPos = 0;
|
||||
if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos)) return;
|
||||
|
||||
var context = new SocketCommandContext(_discord, message);
|
||||
var result = await _commands.ExecuteAsync(context, argPos, _services);
|
||||
|
||||
if (result.Error.HasValue &&
|
||||
result.Error.Value != CommandError.UnknownCommand) // it's bad practice to send 'unknown command' errors
|
||||
await context.Channel.SendMessageAsync(result.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
20
samples/02_commands_framework/Services/PictureService.cs
Normal file
20
samples/02_commands_framework/Services/PictureService.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace _02_commands_framework.Services
|
||||
{
|
||||
public class PictureService
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
|
||||
public PictureService(HttpClient http)
|
||||
=> _http = http;
|
||||
|
||||
public async Task<Stream> GetCatPictureAsync()
|
||||
{
|
||||
var resp = await _http.GetAsync("https://cataas.com/cat");
|
||||
return await resp.Content.ReadAsStreamAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user