How run Multiple c# class files - c#

I have these three class files which I am working on in the bot framework.But when I run my project in the bot emulator only the dialogs of the WelcomeDialog file runs and the other files don't
like if I say hi which is from the WelcomeDialog file I get a corresponding in the emulator but if say Search me something which is from the Bing Search the emulator response with I am unable to understand sorry
I don't know whether the problem is with the message controller file or what
only single cs file works at a time
WelcomeDialog .cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Connector;
using Microsoft.Azure.CognitiveServices.Search;
namespace MyFYP.Dialogs
{
[Serializable] //As bot framework serilaizes and deserializes dialogs
public class WelcomeDialog : IDialog<object>
{
public Task StartAsync(IDialogContext context)
{
context.Wait(PerformActionAsync); // calling PerformActionAsync
return Task.CompletedTask;
}
public async Task PerformActionAsync(IDialogContext context, IAwaitable<object> result)
{ //method
var activity = await result as Activity;
if (activity.Text.Equals("Hello") || activity.Text.Equals("Hi") || activity.Text.Equals("hi") || activity.Text.Equals("hii"))
{
await context.PostAsync("Welcome to the Chatbot Portal of LMS");
}
else if (activity.Text.Equals("How are you"))
await context.PostAsync("I am doing well AlhamdULLILAH what I can do for you");
else if (activity.Text.Equals("what can you do") || activity.Text.Equals("What services you provide"))
await context.PostAsync("i CAN OFFER A COUPLE OF SERVICES ");
else await context.PostAsync("I am unable to understand you");
}
}
}
BingSearch.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Connector;
using Microsoft.Azure.CognitiveServices.Search;
namespace MyFYP.Dialogs
{
[Serializable] //As bot framework serilaizes and deserializes dialogs
public class BingSearch : IDialog<object>
{
private string searchtype = string.Empty;
private string query = string.Empty;
private const string BING_KEY = "3b681ec3e2ed47f3930493d261a28e6d";
private const string searchWeb = "Search Web";
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageActionAsync); // calling PerformActionAsync
return Task.CompletedTask;
}
private async Task MessageActionAsync(IDialogContext context, IAwaitable<object> result)
{ //method
var activity = await result as Activity;
if (activity.Text.Equals("Search me something") || activity.Text.Equals("i want some material"))
{
PromptDialog.Choice(
context: context,
resume: ResumeAfterSearchTypeSelecting,
prompt: "Select searcht type you want to perform",
options: new List<string>
{
searchWeb
}
);
}
}
private async Task ResumeAfterSearchTypeSelecting(IDialogContext context, IAwaitable<string> result)
{
searchtype = (await result) as string;
PromptDialog.Text(
context: context,
resume: ResumeAfterEnteringQuery,
prompt: "Enter your query"
);
}
private async Task ResumeAfterEnteringQuery(IDialogContext context, IAwaitable<string> result)
{
query = (await result) as string;
switch (searchtype)
{
case searchWeb:
{
await BingSearchHelper.SearchWebAsync(context, BING_KEY, query);
break;
}
}
context.Wait(MessageActionAsync);
}
}
}
BingSearchHelper.cs
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Connector;
using Microsoft.Azure.CognitiveServices.Search.WebSearch;
using Microsoft.Azure.CognitiveServices.Search.WebSearch.Models;
namespace MyFYP.Dialogs
{
public class BingSearchHelper
{
public async static Task SearchWebAsync(IDialogContext context,string key,string query)
{
IWebSearchClient client = new WebSearchClient(new ApiKeyServiceClientCredentials(key));
var result = await client.Web.SearchAsync(query:query, count:3, safeSearch: SafeSearch.Strict);
if(result?.WebPages?.Value?.Count>0)
{
await context.PostAsync($"Here is top 3 results for {query} ");
foreach(var item in result.WebPages.Value)
{
HeroCard card = new HeroCard
{
Title = item.Name,
Text = item.Snippet,
Buttons = new List<CardAction>
{
new CardAction(ActionTypes.OpenUrl,"Open Page",value:item.Url)
}
};
var message = context.MakeMessage();
message.Attachments.Add(card.ToAttachment());
await context.PostAsync(message);
}
}
}
}
}

In WelcomeDialog.cs you are calling context.Wait(PerformActionAsync ) which is executing the WelcomeDialog.PerformActionAsync function. Replace PerformActionAsync with BingSearchHelper.SearchWebAsync if you would like to run that function instead.
context.Wait(BingSearchHelper.SearchWebAsync);
To answer the bigger question of "How to run Multiple C# class files", you will typically do it one of two ways.
By creating an instance of that class and calling functions from that instance
Animal dog = new Animal();
dog.Sit();
Or if that function you want to call is static (meaning a class object doesn't need to be created like in the first example), you can simply call the class name followed by the function
Animal.Sit();

Related

getting CS1503 when im trying to create a rest api from a tutorial

I'm trying to communicate with my node js backend from my Xamarin forms app from a tutorial and getting the following error
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'Kula.MainPage' to 'Android.Content.Context' Kula C:\Users\1243g\Desktop\Kula\Kula\Kula\Kula\MainPage.xaml.cs 28 Active
The error is under this in Mainactivity
I was wondering what I am doing wrong because this is the first time I'm trying to create a rest API code below. I think I'm close. So any implementation on how to use the right variables and fix it would be extremely helpful
Main
using Kula.API;
using Refit;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Kula
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
// set variables
Entry RinputEmail;
Entry RinputPassword;
IMyAPI myAPI;
APIRequestHelper apiRequestHelper;
public MainPage()
{
InitializeComponent();
myAPI = RestService.For<IMyAPI>("");
apiRequestHelper = new APIRequestHelper(this , myAPI);
RinputEmail = this.FindByName<Entry>("Remail");
RinputPassword = this.FindByName<Entry>("Rpassword");
}
async private void GTLogin_Clicked(object sender, EventArgs e)
{
//navigate to Login page
await Navigation.PushAsync (new Login());
}
async private void registerUser_Clicked(object sender, EventArgs e)
{
await apiRequestHelper.RequestRegisterUserAsync((RinputEmail.Text).ToString(), (RinputPassword.Text).ToString());
}
}
}
API request helper (one for login one for register)
using Android.Content;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Kula.API
{
public class APIRequestHelper
{
Context context;
IMyAPI myAPI;
public APIRequestHelper(Context context, IMyAPI myAPI)
{
this.context = context;
this.myAPI = myAPI;
}
public async Task RequestRegisterUserAsync(string email, string password)
{
if (string.IsNullOrEmpty(email))
{
Toast.MakeText(context, "no email detected", ToastLength.Short).Show();
}
if (string.IsNullOrEmpty(password))
{
Toast.MakeText(context, "no password detected", ToastLength.Short).Show();
}
//create params for request
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("email", email);
data.Add("password", password);
string result = await myAPI.RegisterUser(data);
}
public async Task RequestLoginUserAsync(string email, string password)
{
if (string.IsNullOrEmpty(email))
{
Toast.MakeText(context, "no email detected", ToastLength.Short).Show();
}
if (string.IsNullOrEmpty(password))
{
Toast.MakeText(context, "no password detected", ToastLength.Short).Show();
}
//create params for request
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("email", email);
data.Add("password", password);
string result = await myAPI.LoginUser(data);
}
}
}
MyAPI
using Refit;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Kula.API
{
public interface IMyAPI
{
[Post("/register")]
Task<string> RegisterUser([Body(BodySerializationMethod.UrlEncoded)] Dictionary<string, object> data);
[Post("/login")]
Task<string> LoginUser([Body(BodySerializationMethod.UrlEncoded)] Dictionary<string, object> data);
}
}

Valid KnowledgeBaseId and SubscriptionKey not provided

I need help, after migrating to the new QNAMaker, im now getting an error: Valid KnowledgeBaseId and SubscriptionKey not provided. Use QnAMakerServiceAttribute or set fields on QnAMakerDialog. What am i missing? Subscription Key and KnowledgebaseID was already added. I simply followed the sample http request upong publishing in the qnamaker portal.
using Microsoft.Bot.Builder.Dialogs;
using QnAMakerDialog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using Microsoft.Bot.Connector;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.CognitiveServices.QnAMaker;
namespace TEST.Dialog
{
[Serializable]
[QnAMaker(authKey:"013ffd97-XXXX-XXXX-981f-ea298085591c", knowledgebaseId:"f81ce668-XXXX-XXXX-XXXX-ad20c5f4d3fa", endpointHostName:"https://XXXX.azurewebsites.net/qnamaker")]
public class QnADialog : QnAMakerDialog<object>
{
public async Task StartAsync(IDialogContext context)
{
context.PrivateConversationData.TryGetValue("Name", out name);
await context.PostAsync($"Hello {name}. The QnA Dialog was started. Ask a question.");
context.Wait(MessageReceivedAsync);
}
public async Task DefaultMatchHandler(IDialogContext context, string originalQueryText, QnAMakerResult result)
{
try
{
// ProcessResultAndCreateMessageActivity will remove any attachment markup from the results answer
// and add any attachments to a new message activity with the message activity text set by default
// to the answer property from the result
// var messageActivity = ProcessResultAndCreateMessageActivity(context, ref result);
if (result.Score > 30 && result.Answer != NOMATCH)
{
await context.PostAsync(result.Answer);
context.Wait(this.MessageReceived);
return;
}
else
{
await context.Forward(new RootLuisDialog(), DialogsCompleted, context.Activity, CancellationToken.None);
}
}
catch (Exception ex)
{
throw;
}
}
public override async Task NoMatchHandler(IDialogContext context, string originalQueryText)
{
try
{
await context.Forward(new RootLuisDialog(), DialogsCompleted, context.Activity, CancellationToken.None);
}
catch (Exception ex)
{
throw;
}
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
//await context.PostAsync($"You sent {activity.Text} which was {length} characters");
context.Wait(this.MessageReceived);
return;
}
private async Task DialogsCompleted(IDialogContext context, IAwaitable<object> result)
{
var success = await result;
//if (!(bool)success)
// await context.PostAsync("I'm sorry. I didn't understand you.");
//context.UserData.Clear();
context.Wait(MessageReceived);
}
[QnAMakerResponseHandler(30)]
public async Task LowScoreHandler(IDialogContext context, string originalQueryText, QnAMakerResult result)
{
//await context.PostAsync($"I found an answer that might help: {result.Answer}");
await context.Forward(new RootLuisDialog(), DialogsCompleted, context.Activity, CancellationToken.None);
//context.Wait(MessageReceived);
}
}
}
RootDialog that calls QNAMaker:
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.FormFlow;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace Test.Dialog
{
[Serializable]
public class RootDialog : IDialog<object>
{
public string name = string.Empty;
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
try
{
//Some User Code that retreives user via PrivateConversationData
//Calls QNADialog
context.Call(new QnADialog(), MessageReceivedAsync);
}
}
}
My Version of CognitiveServices:
Microsoft.Bot.Builder.CognitiveServices.1.1.7
Bot Builder,Bot Connector :3.15.2.2
QNADialog: 1.2.0
As explained on the Generally Available announcement, you can still use Microsoft.Bot.Builder.CognitiveServices package in your code: the code has been changed to handle bot v1 to v3 calls and new v4 (GA version).
You just have to add the necessary information, that is to say the endpoint hostname as previously it was hosted on Microsoft side.
So your dialog code will look like the following (see Github official sample here):
[Serializable]
[QnAMaker("set yout authorization key here", "set your kbid here", <score threshold>, <number of results>, "endpoint hostname")]
public class SimpleQnADialog : QnAMakerDialog
{
}
It seems that you are using QnAMakerDialog with QnA Maker service v4.0, but in description of NuGet package QnAMakerDialog and GitHub readme of QnAMakerDialog (updated to work with QnA Maker v3 API), we can find that this QnAMakerDialog nugget package can work with v3 of the QnA Maker API, not QnA Maker service v4.0.
To work with QnA Maker service v4.0, as Nicolas R said, you can use this NuGet package: Microsoft.Bot.Builder.CognitiveServices to create your QnAMakerDialog.
[Serializable]
public class QnADialog : QnAMakerDialog
{
public QnADialog() : base(new QnAMakerService(new QnAMakerAttribute("{qnaAuthKey_here}", " {knowledgebaseId_here}", "No good match in FAQ.", 0.5, 1, "https://xxxx.azurewebsites.net/qnamaker")))
{ }
//other code logic
}

How do I redirect the message to the corresponding LUIS app

I have a bot with a root LuisDialog and 4 more LuisDialogs each one with a different LUIS model. Following the conversation started here I've implemented a similar DialogFactory strategy.
When a user sends a question that matches "None" intent in my root dialog, I evaluate the rest of dialogs until I find a match and then forward the message to the "winner".
The problem I'm facing is that I'm getting the http error: 429 (Too Many Requests) when querying LUIS (BaseDialog class).
Any ideas about how to face this?
The "None" intent in my root dialog:
[LuisIntent("None")]
public async Task None(IDialogContext context, IAwaitable<IMessageActivity> message, LuisResult result)
{
var activity = await message;
var factory = new DialogFactory();
BaseDialog<object> dialog = await factory.Create(result.Query);
if (dialog != null)
{
await context.Forward(dialog, EndDialog, activity, CancellationToken.None);
}
else
{
await context.PostAsync("No results!");
}
}
public static async Task EndDialog(IDialogContext context, IAwaitable<object> result)
{
//...
}
The DialogFactory class:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading.Tasks;
namespace CodeBot.Dialogs
{
public class DialogFactory
{
private static object _lock = new object();
private static List<BaseDialog<object>> Dialogs { get; set; }
public async Task<BaseDialog<object>> Create(string query)
{
query = query.ToLowerInvariant();
EnsureDialogs();
foreach (var dialog in Dialogs)
{
if (await dialog.CanHandle(query))
{
return dialog;
}
}
return null;
}
private void EnsureDialogs()
{
if (Dialogs == null || (Dialogs.Count != 4))
{
lock (_lock)
{
if (Dialogs == null)
{
Dialogs = new List<BaseDialog<object>>();
}
else if (Dialogs.Count != 4)
{
Dialogs.Clear();
}
Dialogs.Add((BaseDialog<object>)Activator.CreateInstance(typeof(Dialog1));
Dialogs.Add((BaseDialog<object>)Activator.CreateInstance(typeof(Dialog2));
Dialogs.Add((BaseDialog<object>)Activator.CreateInstance(typeof(Dialog3));
Dialogs.Add((BaseDialog<object>)Activator.CreateInstance(typeof(Dialog4));
}
}
}
}
}
And finally, the BaseDialog class (where I'm getting the error):
using Microsoft.Bot.Builder.Dialogs;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Luis;
using System;
namespace CodeBot.Dialogs
{
[Serializable]
public class BaseDialog<R> : LuisDialog<R>
{
public LuisModelAttribute Luis_Model { get; private set; }
public BaseDialog(LuisModelAttribute luisModel) : base(new LuisService(luisModel))
{
Luis_Model = luisModel;
}
public async Task<bool> CanHandle(string query)
{
try
{
var tasks = services.Select(s => s.QueryAsync(query, CancellationToken.None)).ToArray();
var results = await Task.WhenAll(tasks); <-- Error!!!
var winners = from result in results.Select((value, index) => new { value, index })
let resultWinner = BestIntentFrom(result.value)
where resultWinner != null
select new LuisServiceResult(result.value, resultWinner, this.services[result.index]);
var winner = this.BestResultFrom(winners);
return winner != null && !winner.BestIntent.Intent.Equals(Constants.NONE, StringComparison.InvariantCultureIgnoreCase);
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine($"CanHandle error: {e.Message}");
return false;
}
}
}
}
The 429 error is caused by your application (key) hitting the LUIS API too heavily.
You need to either throttle your requests to ensure you stay below the threshold of the free tier, or upgrade to the Basic plan which allows 50 requests a second.

There was an error sending this message to your bot: HTTP status code InternalServerError

my bot suddenly stopped wirking ...
I have create a bot using botframework, luis.ai c# . I have deploy in azure .
The bot was working very good , but now i get this code when i send a message to my bot : There was an error sending this message to your bot: HTTP status code InternalServerError .
I try to generate another key in my luis.ai and i added in my code ...but still i have the same problem .
P.S my botframework is updated with the last version.
MessagesController.cs :
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
namespace FirstBotApplication
{
//[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new AllTheBot());
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
private Activity HandleSystemMessage(Activity message)
{
if (message.Type == ActivityTypes.DeleteUserData)
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (message.Type == ActivityTypes.ConversationUpdate)
{
}
else if (message.Type == ActivityTypes.ContactRelationUpdate)
{
// Handle add/remove from contact lists
// Activity.From + Activity.Action represent what happened
}
else if (message.Type == ActivityTypes.Typing)
{
// Handle knowing tha the user is typing
}
else if (message.Type == ActivityTypes.Ping)
{
}
return null;
}
}
}
AllTheBot.cs
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace FirstBotApplication
{
// [LuisModel("Please Enter Your LUIS Model ID", "Please Enter Your LUIS
Subscription Key")]
[Serializable]
[LuisModel("xxxxxxxx",
"yyyyyyy")]
public class AllTheBot : LuisDialog<object>
{
// internal static string results;
[LuisIntent("None")]
[LuisIntent("")]
public async Task None(IDialogContext context, LuisResult result)
{
string message = $"Sorry, I did not understand '{result.Query}'. Please reformulate your question";
await context.PostAsync(message);
context.Wait(this.MessageReceived);
}
// private const string HeroCard = "Hero card";
[LuisIntent("grettings")]
[LuisIntent("intentfr")]
public async Task Greeting(IDialogContext context,
IAwaitable<IMessageActivity> activity, LuisResult result)
{
await context.PostAsync("Welcome ");
context.Wait(MessageReceived);
}`
}}
Does the code you posted here match your code in exactly, if so you may want to look at formatting errors.
I think the main problem is your declaration of
[LuisIntent("grettings")]
[LuisIntent("intentfr")]
public async Task Greeting(IDialogContext context, IAwaitable<IMessageActivity> activity, LuisResult result)
{
await context.PostAsync("Welcome");
context.Wait(MessageReceived);
}
In my experience I'd get errors when I had more than just
IDialogContext and LuisResult as the parameters for a LUIS Task. Try removing IAwaitable<IMessageActivity> activity from your parameters:
[LuisIntent("grettings")]
[LuisIntent("intentfr")]
public async Task Greeting(IDialogContext context, LuisResult result)
{
await context.PostAsync("Welcome");
context.Wait(MessageReceived);
}
I had the same issue. i ended up recreating the bot and restarting my machine. worked like a charm

(Discord bot 1.0 c#) How to make a new class and add cmds?

Hello there Stackoverflow! (first time posting here so plz be nice :P)
So, I've decided to make a discord bot 1.0 in c# (i'm learning c# atm) and I have gotten in to a problem and i'm not sure how to fix it..
So, to describe what i'm trying to do is following.
I'm trying to make it so i can have different classes for x commands such as .say etc instead of having em all in the "commands" one below so its a bit easier to work with.
I got these working three scripts but cant get the fourth to work
//Startup
using System;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
using Discord.Commands;
namespace MyBot
{
public class Program
{
// Convert our sync main to an async main.
public static void Main(string[] args) =>
new Program().Start().GetAwaiter().GetResult();
private DiscordSocketClient client;
private CommandHandler handler;
public async Task Start()
{
// Define the DiscordSocketClient
client = new DiscordSocketClient();
var token = "Censored";
// Login and connect to Discord.
await client.LoginAsync(TokenType.Bot, token);
await client.StartAsync();
var map = new DependencyMap();
map.Add(client);
handler = new CommandHandler();
await handler.Install(map);
// Block this program until it is closed.
await Task.Delay(-1);
}
private Task Log(LogMessage msg)
{
Console.WriteLine(msg.ToString());
return Task.CompletedTask;
}
}
}
//My command handler
using System.Threading.Tasks;
using System.Reflection;
using Discord.Commands;
using Discord.WebSocket;
namespace MyBot
{
public class CommandHandler
{
private CommandService commands;
private DiscordSocketClient client;
private IDependencyMap map;
public async Task Install(IDependencyMap _map)
{
// Create Command Service, inject it into Dependency Map
client = _map.Get<DiscordSocketClient>();
commands = new CommandService();
_map.Add(commands);
map = _map;
await commands.AddModulesAsync(Assembly.GetEntryAssembly());
client.MessageReceived += HandleCommand;
}
public async Task HandleCommand(SocketMessage parameterMessage)
{
// Don't handle the command if it is a system message
var message = parameterMessage as SocketUserMessage;
if (message == null) return;
// Mark where the prefix ends and the command begins
int argPos = 0;
// Determine if the message has a valid prefix, adjust argPos
if (!(message.HasMentionPrefix(client.CurrentUser, ref argPos) || message.HasCharPrefix('!', ref argPos))) return;
// Create a Command Context
var context = new CommandContext(client, message);
// Execute the Command, store the result
var result = await commands.ExecuteAsync(context, argPos, map);
// If the command failed, notify the user
if (!result.IsSuccess)
await message.Channel.SendMessageAsync($"**Error:** {result.ErrorReason}");
}
}
}
//Commands
using System;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace MyBot.Modules.Public
{
public class PublicModule : ModuleBase
{
[Command("invite")]
[Summary("Returns the OAuth2 Invite URL of the bot")]
public async Task Invite()
{
var application = await Context.Client.GetApplicationInfoAsync();
await ReplyAsync(
$"A user with `MANAGE_SERVER` can invite me to your server here: <https://discordapp.com/oauth2/authorize?client_id={application.Id}&scope=bot>");
}
[Command("leave")]
[Summary("Instructs the bot to leave this Guild.")]
[RequireUserPermission(GuildPermission.ManageGuild)]
public async Task Leave()
{
if (Context.Guild == null) { await ReplyAsync("This command can only be ran in a server."); return; }
await ReplyAsync("Leaving~");
await Context.Guild.LeaveAsync();
}
}
}
//This is the one i want to work but i only get "Unknown command" as error?
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace MyBot.Modules.Public
{
class test : ModuleBase
{
[Command("say")]
[Alias("echo")]
[Summary("Echos the provided input")]
public async Task Say([Remainder] string input)
{
await ReplyAsync(input);
}
}
}
If you know what i do wrong please tell me or reefer me to some info about the problem and i can try fix it :)
Thanks in advance!
PS, im sorry if there is a dupe of this question but i don't know what to search for to find it
EDIT
I've been told to "Pit the metohds (cmds) in the class" but how would i go around todo that?
The answer is following
Add Public before the class {name}so it would be
namespace MyBot.Modules.Public
{
**Public** class test : ModuleBase
{
[Command("say")]
[Alias("echo")]
[Summary("Echos the provided input")]
public async Task Say([Remainder] string input)
{
await ReplyAsync(input);
}
}
}

Categories

Resources