Discord Bot command cooldown - c#

I'm trying to add a cooldown on on my ~hunt command for my Discord Bot. Which only can be used once in 5 minutes. I've tried different ways to program it but it doesn't work for me. Does anyone know a way to add an cooldown on a Discord command. Im currently using c# for it.

I would save something like this in a database with the UUID and the timestamp when the last request was processed successfully by this User.
On the next request just check if the User is in the database and the last request is older than 5mins.

You will need a way of storing the GuildId and UserId of the user who called the command as well as the discord bot server time that the method was called. Then whenever that function is called, you check with the data and if the user data matches then see how much time has passed since last time.

Related

How to share attachments from user to agent (Human handoff) using Bot?

i have bot made using c#. It has the feature of human off. We have integrated the solution provide by tompanna of human handoff where a agent can talk to single user at a time.Here the link of solution we used for human handoff https://github.com/tompaana/intermediator-bot-sample. Our bot is working fine and able to talk with agent with the help of this solution but major issue come when a user want to share image or any kind of attachments from user to agent or from agent to user. The bot show that image is send but user is not able to see it. Simpler case happen in the case of agent.
Image of agent while sending a attachment to user.
And also the image of user ,unable to see the image send by agent.
The sample which you are using for Human HandOff has not been updated over a year, so it gets difficult to be able to find solutions for supporting various features pertaining to the same. However, going through the sample issues, there has been a similar issue in which the sample does not support emojis, images or files to the receiving user. If a user sends any of the above mentioned features, the receiver will get a blank message as it supports only text messages.
Th tentative solution suggested by a user is to create a simple method extension to send image/file messages.You could go ahead and give it a try to see if it works for your case.
Hope this helps.
You need to edit the source code of the library to achieve what you are trying.
In this MessageRouter file , method RouteMessageIfSenderIsConnectedAsync , you can access message.Attachments , then pass it as a parameter to SendMessageAsync in line 432, then from SendMessageAsync in line 160 , you can pass it to CreateMessageActivity method and then in file ConnectorClientMessageBundle , you can access the attachment and attach it to messageActivity.

How to send email and roll back changes?

I am creating a complaint registration form for user in asp.net MVC. The complaint is send to user email address and complaint is save into SQL server 2017 database. I need a suggestion.
my question is, How do I handle email and database?
condition 1 - what if database fails to save data but email is sending.
condition 2 - what if database save data to table but fails to send email.
How I did,
public void MyFunction()
{
try {
var db = DbContext();
//some code
//The number of state entries written to database
int entities = db.SaveChanges();
if (entities > 0)
{
SendEmail();//what fails to send email and complaint is created.
}
}
catch(Exception ex)
{
//exception is handle
}
}
When db.SaveChanges() is done, it return how many tables are written to database. From my homework, Second condition is most important.
The Result I want is, both process of creation and sending email is handle smoothly.
Is I am on right path or not?
Any suggestion is appreciated.
What I would do in this case is have the emails saved to a table in the database, and implement a service that reads from that table and sends any unsent emails with a retry count for each entry.
That way you can retry sending the email at any time if it fails.
In real life you'll try to handle the email processes to another service (like sendgrind), so your application will store a request to send an email after the save is done. This request will be handle by your service whenever it can; Also, you won't need to be awaiting for the email to be sent in order to finish the user's request.
Since you're doing a homework you can:
1- [Recommended] store that email in a table and have a small service reading from it, once it found a record, send an email and flagged as done.
2- [Not Fancy] Do it exactly as you are doing it. Save the record and if success send an email.
This is an interesting problem because it asks you to consider trade-offs, probabilities, and perfection vs. what's good enough.
Here's what's good enough: Update the database. If it succeeds, put a message in a queue (which could be another database table) that will result in an email being sent.
You could just send the email directly via SMTP right when the database gets updated, but there's a small chance that due to some odd transient condition the email wouldn't get sent. (That happens - maybe SMTP permissions get messed up and the email gets rejected.) Putting it in a queue with a separate process is a reasonable approach to make sure there's some resilience for your emails.
Why is that only "good enough?" Because nothing is bulletproof. It's still possible that your email might not get sent. After all, we're concerned that the database update might fail. But if we're sending the email by inserting a record into another database that some other process monitors, doesn't that mean that could fail too? What will we do if the first database update succeeds but the one to send the email fails?
That's where we start making trade-offs. It's possible that we might insert a complaint into the database but not send an email. How likely is that, and if it happens, how bad is it? And whatever we might consider doing in response to that unlikely scenario, couldn't that fail too?
That's a rabbit hole. We can endlessly make our code more and more complex trying to account for less and less likely scenarios, but it's not worth it. Eventually bugs in our overly complex code will become the reasons why something doesn't work.
Instead of chasing after that, it makes more sense to realize that sometimes our code will fail because of things we can't control, and to know what that failure will look like. Again, this is a question of what's good enough.
The initial database update fails. The user sees a message saying that their complaint was not saved. Perhaps we can provide them another way to contact us. The exception gets logged so that we can figure out what happened.
The initial database update succeeds, then we send the email message to a queue. The email process fails. That should also get logged. That might be more urgent, because if one email fails, perhaps lots of them are. Hopefully that process provides some sort of alert if it's down so someone can fix the problem.
The initial database update fails, and trying to send the email message to the queue fails. We log that. Again, hopefully there's something to let us know when stuff is failing, even if it's an email digest that someone gets.
Even that can fail. Our logging and our alerts can fail. We can replace them with something more resilient, like a better message queue. But we could drive ourselves insane trying to account for everything when it's impossible. All we can do is try to make our applications reliable and resilient.

C# create tor hidden service trough controlport

So I'm making a small chat application like ricochet, but then in C# and I succesfully connect to the tor controlport and create a hidden service id and private key, however after that point i got stuck, I send ADD_ONION NEW:BEST Port=8946,127.0.0.1:8946\r\n to the tor control port and it answers with hidden service id and private key and code 250. But what should I do to make it automatically run the service? I tried googling it but couldnt find anything and all examples are python or c++ if someone could point me in the right direction that would be great. Also, im using Knapcode.TorSharp, so the tor installation is NOT persistent, the user has a profile file where the key etc are saved and it should start from there.
Thanks in advance
When you call ADD_ONION, the hidden service starts running immediately (accessible once it can publish the Hidden Service descriptors and establish circuits [usually within a minute or two]).
If you want those services to start again automatically on subsequent runs (for a non-persisting Tor installation), then you'll need to programatically make similar calls to ADD_ONION when your application restarts and detects that private keys are saved to the profile.
You can re-create hidden services using existing keys with syntax like:
ADD_ONION RSA1024:*PKEY_GOES_HERE* Flags=DiscardPK Port=8946,8946
When you call ADD_ONION the first time, the response should look something like:
250-ServiceID=abcdefg123456
250-PrivateKey=RSA1024:MIICXAIBAAKBgQC91z4mjpNF5ddRL6jm7rnmgwSiQ6dNXF1Fo8sz1wOsGqWKgE4C6Bd3KT+zgQgXJlioIJOCEP9D0b/qlPCvEiGG3/fPEn1+Zpf5N4oNRI+in7J2m3xihhgAinbscJ0vM+1vfnRLlMrtYdE9J5aKle+t+OC6ZoXTxzPZRZkmXtqVpp8QIDAQPXAoGBAK7oh8zChBJch5u3i6jpvsIRaM2QA68VMKKfHPOwYSPKkUcgm7+10xjpGlXqxmd93yVYjk/CFU6JDIe3nmHPFK82BtPgyEMRtmVmcunS262Ead/ffpzAErBSdihOF7zO/wGjGgIaMW9Bhy69aK5LcNUB30Iu9+MWG62xz8tTgcEhAkEA8QNKMyKdRUbgGc9Gv1n8JtMs0Af/a/OHozdn1ywvHxw7mzahF936gqHIdg67XLtIj5TaUSM/44OoEvvURnG7QJBAMmlVttRd8y+/FnA6dPkesQMpPw+ipHLNUrf7qPrX3py670vLbprWDNYCOn6oaxoRtl/iRXPI5CgjMXmnu356pUCQDnWD0VMJi+MvZSUACbZXwP2ApP1bHfla3I7Xaezh5oDxtoAd0PS4STh1+HQUPvQW4WfLUcSsz9UaMAg2NI+fFUCQc7D1PVW7sqSGBth3jXE+3+H6WY2iy8Z1Ji+l2KRdJ8IiIOWdfcgUpMNzZV8jc7Y9Cm5p5l2wy7kjfGADyYBCXkCQD9fnmVMlUO1xITfW8K+pAf6FPcvfo8J0rpWHEhG4CxjFw4s4s9Mzjme1e17YnfK21CNIOxd2bkqVI4j4o=
250 OK
You'll want to save what it gave back in PrivateKey, and use this value to restart the hidden services the next time you run your application.

Can multiple WebClient interfere with each other?

I must build a Application that will use Webclient multiple times to retrieve every "t" seconds information from a server.
Here is a small plan to show you what I'm doing in my application:
Connect to the Web Client "USER_LOGIN" that returns me a GUID(user unique ID). I save it and keep it to use it in future Web Client calls.
Connect to the Web Client "USER_GETINFO" using the GUID I saved before as parameter. This Web Service returns an array of strings holding all my personal user information( my Name, Age, Email, etc...). => I save the array information this way: Textblock.Text = e.Result[2].
Starting a Dispatcher.Timer with a 2 seconds Tick to start my Loop. (Purpose of this is to retrieve information and update it every 2 seconds)
Connect to the Web Client "USER GETFRIEND", wich is in my Timer, giving him the GUID as parameter. It returns me an array filled with my friends informations(Name, email, message, etc...). I inserted this WebClient in the timer so my friend list refreshes every 2 seconds.
I am able to create all the steps without any error until step 3. When I call the "USER_GETFRIEND" Web Client I am facing two major problems:
On one side I noticed that my number of Thread increased dramatically. => I always thought that when a WebClient had finished its instructions it would shut down by itself, but apparently that does not happen in Asyncronous calls.
And on the other side I was surprised to see that using the same proxy for two Webclient calls(ie: if i declare test.MainSoapClient proxy = new test.MainSoapClient()), the data i would retrieve from "USER_GETFRIEND" e.Result, was sent directly to my "USER_GETINFO" array. And so my Name and Email adresses on the UI were replaced by the same value in the USER_GETFRIEND array. So my Name is changed to my friends email and so on...
I would like to know if it's possible to close a WebClient call(or Thread) that I am not using anymore to prevent any conflicts? Or if someone has any suggestion concerning my code and the way i should develop my application please feel free to propose.
I got the answer a few weeks ago and figured out it was important to answer my own question.
My whole problem was that I wasn't unsubscribing from my asynchronous calls and that I was using the same proxy class from "Add Service reference":
So when I was using:
proxy.webservice += new Eventhandler<whateverinhere>(my_method);
I never did:
proxy.webservice -= new Eventhandler<whateverinhere>(my_method);
Hope it will help someone.

Sending Periodic Mail according to user's Setting in ASP.net?

in my web-application I want to send mail for users according to pre selected periods by themselves. for example: 1 HTML Mail Per 3days to user 01 and 1 HTML Mail Per 20days to user 02
how can I perform that? any resources? I can send mail by my app from My Gmail Account to any mail addresses in my tables but i dont know how to send it automatically in a period of time.(i use C# and SQL Express)
Help me out!
I found the Solution. according to my search we have 3 ways to handle that:
working with SQL Server to send mail notification in periods of time.(or this)
using Windows service and Creating Timer object and checking the time with it.
but in ways 1 and 2 we should access to server and we need dedicated hosting server to for example installing WinService on it. so it does not work in a sharing Host space we usually use. So I Found the best way as you see:
3. Simulating Windows Services Using ASP.NET Caching For Scheduled Jobs.
the link above is a terrific solution. So there is no need to work out-side of our web application.
You will need something which can periodically run jobs for you, like a cron daemon or windows task scheduler.
Essentially you have the periodic job kick off and do whatever mail handling you need.
You can also do this from code if you can create a windows service to basically sleep until the next batch of mails needs to be sent.
The easiest is to write the task scheduler or cron job to run periodically. In that way you just need a small piece of code to handle the mail sending portion and then you just schedule it to run once an hour or day or whatever needed.
Hai,
Have a look at quartz.net
Quartz.NET is a full-featured, open source job scheduling system that can be used from smallest apps to large scale enterprise systems.
Quartz.NET is a port of very propular open source Java job scheduling framework, Quartz. Quartz.NET supports clustering and database persistence out-of-the-box and has powerful means to schedule jobs using cron like expressions, interval triggers and exclusion advices.
The great thing about IIS hosted ASP.NET is that IIS will (by default) periodically recycle your application pool according to the settings on the app pool itself.
When your application pool is starting (which could be at least once a day especially if it's allowed to idle i.e. a business app where most activity is 9-5) the Application_Start event-handler in Global.asax is fired. This could be used for your recurring task.
Now you don't necessarily want to run this email send synchronously within that Application_Start handler because to me it seems this messaging functionality is not core to the startup but by all means use this event-handler as an easy way to periodically do your housekeeping.
To send async you should use async delegates for example.
i think there a solution:
1- you have to add 2 column in the user table in your sql db if you have a user table and in the first column add the date of the last email sent to the user and the second column has the period for sending the email for that user for ex:
LastEmailSentDate datetime
SendEmailPeriod int
2- in your application code write a function that compare the last date of the last sent email with the period of the sending the email.
// here the funciton code
public void CompareLastSentDate()
{
// lets assume that you bring the data for the db using Sqdatareader reader
//get the field from the LastEmailSentDate field in the database as i mention before
DateTime LastEmailSentDate = Convert.ToDate(reader["DatePeriod"])
// get the field from the SendEmailPeriod of the user field from database
int sendEmailPeriod = Convert.Toint32(reader["SendEmailPeriod"])
// now you have the date before the period of day ex: before 3 days depend on user
DateTime DatePeriod = new DateTime(DateTime.Now.Year, DateTime.Now.Month, (DateTime.Now.Day - sendEmailPeriod ));
// if the last email send is before period of day that mean u have to send an email again
if(LastEmailSentDate.Day <= DatePeriod.Day)
{
// sent the email to the user
}
}
note: now u can loop among the users and sent the email
you can call this function once in a day by calling it from ur app home page Page_Load event and after the first call of the day add an application["LastFunctionCallDate"] = DateTime.Now flag so in the next you can check this flag if its == today and if not call it again

Categories