error using IAsyncEnumerable<IReadOnlyCollection<IUser>> in discord bot - c#

i have this code line
if (channel.GetUsersAsync().Contains(Program.kami.CurrentUser as IGuildUser))
do something;
it writes an exception which says IAsyncEnumerable> doesnt contain the definition of contains
and i dont know what to do
[Command("join", RunMode=RunMode.Async), Summary("joins voice channel")]
public async Task joinvoice([Remainder, Summary("The text to echo")] string searchP="")
{
IVoiceChannel channel = (CommandHandler.Last as IGuildUser).VoiceChannel;
if (channel == null)
{
await ReplyAsync("u have to be in a channel first");
return;
}
string choice = "";
VideoSearch SearchRisolts = new VideoSearch();
if (searchP != "")
{
if (searchP.Contains("https://"))
choice = searchP;
else
{
List<VideoInformation> video = SearchRisolts.SearchQuery(searchP, 1);
await ReplyAsync("* " + video[0].Title + "\n\n* " + video[1].Title + "\n\n* " + video[2].Title);
//choice = video[int.Parse() - 1].Url;
}
this.Context.Channel.GetMessagesAsync(1).First();
}
IAsyncEnumerable<IReadOnlyCollection<IUser>> x = channel.GetUsersAsync();
if ((await channel.GetUsersAsync()).Contains(Program.kami.CurrentUser as IGuildUser))
var audioClient = await channel.ConnectAsync();
await SendAsync(audioClient,choice);
}

You need to await a GetUserAsync operations
(await channel.GetUsersAsync()).Contains(....)
Be sure that your method is async.

Related

return string after a request to firebase in Unity / c#

Does anyone know how to return a value of a get to a Firebase Database after it is completed?
I want for example to return the string "extracted.pl_superhit" to another class and it's an async process...
public void LoadData_element(string player)
{
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
FirebaseDatabase.DefaultInstance.GetReferenceFromUrl(DATA_URL).GetValueAsync()
.ContinueWith((task =>
{
if (task.IsFaulted)
{
print("Falhou o Load dos dados");
}
if (task.IsCanceled)
{
print("Cancelou o load dos dados");
}
if (task.IsCompleted)
{
DataSnapshot datasnap = task.Result;
string pData = datasnap.GetRawJsonValue();
var humidval = datasnap.Child(player).GetRawJsonValue();
string test = humidval.ToString();
print("x:" + test);
Firebase_Database_Player extracted = JsonUtility.FromJson<Firebase_Database_Player>(test);
print("Player_name:" + extracted.pl_name);
print("Player_lfbar:" + extracted.pl_lfbar);
print("Player_hit:" + extracted.pl_hit);
print("Player_superhit:" + extracted.pl_superhit);
print("Player_defend:" + extracted.pl_defend);
print("Player_atuallife:" + extracted.pl_atuallife);
print("Player_atualattack:" + extracted.pl_atualattack);
}
}));
}
thanks
Make the function async and await the necessary calls
public async Task<string> LoadData_element(string player) {
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
var reference = FirebaseDatabase.DefaultInstance.GetReferenceFromUrl(DATA_URL);
DataSnapshot datasnap = await reference.GetValueAsync()
string pData = datasnap.GetRawJsonValue();
var humidval = datasnap.Child(player).GetRawJsonValue();
string test = humidval.ToString();
print("x:" + test);
Firebase_Database_Player extracted = JsonUtility.FromJson<Firebase_Database_Player>(test);
print("Player_name:" + extracted.pl_name);
print("Player_lfbar:" + extracted.pl_lfbar);
print("Player_hit:" + extracted.pl_hit);
print("Player_superhit:" + extracted.pl_superhit);
print("Player_defend:" + extracted.pl_defend);
print("Player_atuallife:" + extracted.pl_atuallife);
print("Player_atualattack:" + extracted.pl_atualattack);
return extracted.pl_superhit;
}

Xamarin forms Crash when user exit screen and come back after PUT process

My XF app crash when user try to open any screen after finishing update data in one specific screen, the others works well.
Only I got is :
"08-20 23:41:19.211 W/art (15347): JNI RegisterNativeMethods: attempt to register 0 native methods for android.runtime.JavaProxyThrowable".
No HokeyApp message received in my email and no extra information appears so I can solve the problem, just crash and close the app.
I tried to decrease the amount of requests to local database, tried to follow step by step the execution process so I could get any clue about causes.
Task act = Task.Run(async () => await App.DataService.UpdateItemAsync(CP, ToServer, "Contact_Party/EditContact_Party/" + CP.Id));
await act.ContinueWith(async (antecedent) =>
{
foreach (var sam in specialty)
{
if (CP.Id > 0)
{
sam.Cntct_SEQ = CP.Id;
}
else
{
sam.Tmp_Cntct_SEQ = CP.Cntct_SEQ;
}
if (sam.Id == 0)
{
if (sam.Cntct_Spec_SEQ == 0)
await App.DataService.CreateItemAsync(sam, ToServer, "Contact_Specialty/AddContact_Specialty");
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
}, TaskContinuationOptions.None);
Below is the other code or the final step in Update data...
public async Task<T> UpdateItemAsync<T>(T item, bool ToServer, string url) where T : BaseModel, new()
{
try
{
HttpResponseMessage hrm = new HttpResponseMessage();
if (!CrossConnectivity.Current.IsConnected)
ToServer = false;
if (ToServer)
{
RestURL = PrimaryRestURL;
RestURL += url;
var content = JsonConvert.SerializeObject(item);
content = content.Replace("null", " ");
try
{
hrm = await _client.PutAsync(RestURL, new StringContent(content, System.Text.Encoding.UTF8, "application/json"));
RestURL = PrimaryRestURL;
}
catch (Exception hre)
{
RestURL = PrimaryRestURL;
ContentPage page = new ContentPage();
string inner = "", source = "", trace = "", data = "";
if (hre.InnerException != null)
inner = hre.InnerException.Message;
data = hre.Data.ToString();
source = hre.Source;
trace = hre.StackTrace;
string msg = "RestURL: " + RestURL + "\n\n Data: " + data + "\n\n Message: " + hre.Message + "\n\n Source: " + source + "\n\n Trace: " + trace + "\n\n Inner Message: " + inner;
await page.DisplayAlert("Error", msg, "Ok");
}
if (hrm.StatusCode == System.Net.HttpStatusCode.OK || hrm.StatusCode == System.Net.HttpStatusCode.NoContent)
{
item.Updated = true;
await database.UpdateAsync(item);
DependencyService.Get<IMessage>().LongAlert("Completed");
}
else
{
item.Changed = true;
await database.UpdateAsync(item);
DependencyService.Get<IMessage>().LongAlert("Error connection to server");
}
}
else
{
item.Changed = true;
await database.UpdateAsync(item);
DependencyService.Get<IMessage>().LongAlert("Completed");
}
}
catch (Exception xc)
{
ContentPage page = new ContentPage();
string inner = "", source = "", trace = "", data = "";
if (xc.InnerException != null)
inner = xc.InnerException.Message;
data = xc.Data.ToString();
source = xc.Source;
trace = xc.StackTrace;
string msg = "RestURL: " + RestURL + "\n\n Data: " + data + "\n\n Message: " + xc.Message + "\n\n Source: " + source + "\n\n Trace: " + trace + "\n\n Inner Message: " + inner;
await page.DisplayAlert("Error", msg, "Ok");
}
return item;
}
Finally, I solved the issue, it was because I wanted to make the process of updating in a task so being continues with sub updates, after implementeing each update process alone it work ... the code that produced the issue is:
Task act = Task.Run(async () => await App.DataService.UpdateItemAsync(CP, ToServer, "Contact_Party/EditContact_Party/" + CP.Id));
await act.ContinueWith(async (antecedent) =>
{
foreach (var sam in specialty)
{
if (CP.Id > 0)
{
sam.Cntct_SEQ = CP.Id;
}
else
{
sam.Tmp_Cntct_SEQ = CP.Cntct_SEQ;
}
if (sam.Id == 0)
{
if (sam.Cntct_Spec_SEQ == 0)
await App.DataService.CreateItemAsync(sam, ToServer, "Contact_Specialty/AddContact_Specialty");
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
}, TaskContinuationOptions.None);

getting message in a command from the discord chat

I have this line which needs to recieve a message from the discord text channel.
choice = video[int.Parse(CommandHandler.message .Content)-1].Url;
I tried a lot of things, including searching in the api but I don't have a clue.
Here is the command
[Command("join", RunMode= RunMode.Async), Summary("joins voice channel")]
public async Task joinvoice([Remainder, Summary("The text to echo")] string searchP="")
{
IVoiceChannel voicechannel = (CommandHandler.Last as IGuildUser).VoiceChannel;
if (voicechannel == null)
{
await ReplyAsync("u have to be in a channel first");
return;
}
string choice = "";
VideoSearch SearchRisolts = new VideoSearch();
if (searchP != "")
{
if (searchP.Contains("https://"))
choice = searchP;
else
{
List<VideoInformation> video = SearchRisolts.SearchQuery(searchP, 1);
await ReplyAsync("1) " + video[0].Title + "\n\n2) " + video[1].Title + "\n\n3) " + video[2].Title);
choice = video[int.Parse(CommandHandler.message .Content)-1].Url;//here i need to recive a message from the chat
}
}
if (voicechannel != Program.voicechannel)
{
Program.audioClient = await voicechannel.ConnectAsync();
Program.voicechannel = voicechannel;
}
if (Program.audioClient!=null)
await SendAsync(Program.audioClient, choice);
}
The class containing this function should derive from BaseModule<ICommandContext>
This BaseModule contains the Context, which in place contains the message you are looking for.
Context.Message.Content

StorageProgress Report function is not called by GetFileAsync

I'm trying to download resources file for my game from Firebase Storage, and to show downloading progress. But I came to strange behavior of GetFileAsync function. The Report function of StorageProgress is not called periodically during file downloading how it is described in reference. Report function is called during saving to disk, after the file is placed into memory(downloaded). What I'm doing wrong?
string resourcesURL = "URL_TO_RESOURCE_FILE"; // https://firebasestorage.googleapis.com/......
public void UpdateProgress(float val)
{
labelProgress.text = Mathf.RoundToInt(val * 100f) + "%";
circleProgress.fillAmount = val;
}
void OnDownloadClick()
{
SetDownloadingView();
string saveToPath = GetParentFolder() + "/resources.bin";
StorageReference fileRef = FirebaseBackend.Instance.GetStorage().GetReferenceFromUrl(resourcesURL);
StorageProgress<Firebase.Storage.DownloadState> progressHandler = new StorageProgress<Firebase.Storage.DownloadState>(state =>
{
Debug.Log(String.Format ("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
UpdateProgress(state.BytesTransferred / state.TotalByteCount);
});
Task dwnTask = fileRef.GetFileAsync
(
saveToPath,
progressHandler,
CancellationToken.None
);
dwnTask.ContinueWith(resultTask =>
{
if (!resultTask.IsFaulted && !resultTask.IsCanceled)
{
ResetView();
Debug.Log("Download finished!");
}
else
{
ResetView();
Debug.Log("Download fail!");
}
});
}
Unity version is 5.5.0f3
Firebase Unity SDK version is 3.0.1
You may not be doing anything wrong at all.
According to this post, this is a Firebase bug that is to be addressed in the next Firebase update.
Try with an IEnumerator, this is my code with the storage progress working:
protected IEnumerator downloadObject(string target_file, string target_path, int item_index)
{
if (target_file != "")
{
FirebaseStorage storage = FirebaseStorage.DefaultInstance;
string local_url = target_path.Replace("\\", "/").Replace("//", "/");
StorageReference storage_ref =
storage.GetReferenceFromUrl(FB_Conf.gsURL + target_file);
Task task = null;
try
{
task = storage_ref.GetFileAsync(local_url,
new Firebase.Storage.StorageProgress<DownloadState>((DownloadState state) =>
{
// called periodically during the download
long tbyte = state.TotalByteCount;
file_progress = (float)state.BytesTransferred / (float)tbyte;
}), CancellationToken.None);
}
catch (Exception exc)
{
Debug.Log("Get file async error: " + exc.Message);
}
if (task != null)
{
yield return new WaitUntil(() => task.IsCompleted);
task.ContinueWith((resultTask) =>
{
if ((resultTask.IsFaulted) || (resultTask.IsCanceled))
{
error_count++;
string msg = (resultTask.IsCanceled) ? "Download error." : "";
if ((resultTask.Exception != null) &&
(resultTask.Exception.InnerExceptions.Count > 0) &&
(resultTask.Exception.InnerExceptions[0] is Firebase.Storage.StorageException))
msg = ((Firebase.Storage.StorageException)resultTask.Exception.InnerExceptions[0]).HttpResultCode.ToString();
else if (resultTask.Exception != null)
msg = resultTask.Exception.Message;
}
});
}
else
{
error_count++;
}
}
}

Multiple forms in Microsoft bot framework

I have two forms. I need to access both the forms based on the user Input.
The forms are as follows
internal static IDialog<JObject> BuildTravelForm()
{
travelstatus = 1;
leaveStatus = 0;
return Chain.From(() => FormDialog.FromForm(TravelForm.BuildForm))
.Do(async (context, order) =>
{
try
{
travelstatus = 0;
var completed = await order;
string source = (string)completed.GetValue("Question1");
string destination = (string)completed.GetValue("Question2");
await context.PostAsync("Your travel request is awaiting approval" + " " + "from" + " " + source + " " + "to" + " " + destination);
}
catch (Exception)
{
await context.PostAsync("Thank you");
}
});
}
The second one goes like this
internal static IDialog<JObject> BuildLeaveForm()
{
leaveStatus = 1;
travelstatus = 0;
return Chain.From(() => FormDialog.FromForm(LeaveForm.BuildForm))
.Do(async (context,order)=>
{
leaveStatus = 0;
var completed = await order;
string startDate = (string)completed.GetValue("Question1");
string endDate = (string)completed.GetValue("Question2");
await context.PostAsync("Your leave is applied" + " " + "from" + " " + startDate + " " + "to" + " " + endDate);
});
}
The controller method is as follows
public async Task<Activity> Post([FromBody]Activity activity)
{
try
{
if (activity.Type == ActivityTypes.Message)
{
if (leaveStatus == 1 && travelstatus==0)
{
//nested if to check intents to follow
await Conversation.SendAsync(activity, BuildLeaveForm);
}
else if(travelstatus == 1 && leaveStatus==0)
{
await Conversation.SendAsync(activity, BuildTravelForm);
}
else
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
StateClient stateClient = activity.GetStateClient();
string replyMessage = "";
Luis stluis = await GetEntityFromLUIS(activity.Text);
if (stluis.intents.Count() > 0)
{
Activity reply;
///await Conversation.SendAsync(activity, MakeGreetings);
using (var file = Assembly.GetExecutingAssembly().GetManifestResourceStream("Javis_V2.IntentLibrary.json"))
{
o2 = JObject.Parse(new StreamReader(file).ReadToEnd());
string luisIntent = stluis.intents[0].intent;
if (luisIntent == "LeaveManager")
{
await Conversation.SendAsync(activity, BuildLeaveForm);
}
else if(luisIntent=="TravelManager")
{
await Conversation.SendAsync(activity, BuildTravelForm);
}
else
{
leaveStatus = 0;
travelstatus = 0;
replyMessage = (string)o2.GetValue(luisIntent);
if(replyMessage=="")
{
replyMessage = "Sorry! Not getting you";
}
reply = activity.CreateReply(replyMessage);
await connector.Conversations.ReplyToActivityAsync(reply);
}
}
}
}
}
else
{
HandleSystemMessage(activity);
}
return null;
}
catch (Exception exp)
{
Debug.WriteLine(exp);
return null;
}
}
The problem is that when the first form is completed, and when the second form is triggered through luis intent, the first form pops up. I am looking for something without the use of Dialogs.
Any kind of help is appreciated.
Thanks in advance.
This line is the issue :
if (leaveStatus == 1 && travelstatus==0)
{
//nested if to check intents to follow
await Conversation.SendAsync(activity, BuildLeaveForm);
await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Thanks"));
}
else if(travelstatus == 1 && leaveStatus==0)
{
await Conversation.SendAsync(activity, BuildTravelForm);
await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Thanks"));
}
If you see on the above code, the BuildTravelForm or BuildLeaveForm can clearly generate an error and end it without calling the Chain operation Do. If everything executes ok, it will call Do otherwise it will simply skip it. So the best place to reset the status is after the await statement which is ensured to be called after the completion of the dialog.
I will do like this :
if (leaveStatus == 1 && travelstatus==0)
{
//nested if to check intents to follow
await Conversation.SendAsync(activity, BuildLeaveForm);
travelstatus =0; leaveStatus=0;
await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Thanks"));
}
else if(travelstatus == 1 && leaveStatus==0)
{
await Conversation.SendAsync(activity, BuildTravelForm);
travelstatus =0; leaveStatus=0;
await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Thanks"));
}
Do check if it works well.

Categories