Delete a discord message with Webhook C# - c#

How can I delete a discord message with a Webhook? I already added a Webhook send message but I cant find out how to delete the messages that the Webhook sent without opening the app and deleting it manually.

If you're using Discord.Net then deleting a message is handled pretty easily like this:
var sent = await Context.Channel.SendMessageAsync("Hello world!");
await sent.DeleteAsync();

If you are using the DSharpPlus library, the process of deleting a message from a Webhook is very simple!
Just store the value that the method ExecuteAsync(); returns in a variable and then use the method DeleteAsync();
As in this code:
//Here I am creating a Webhook that will send the message "Message to Delete"
DiscordWebhookBuilder WebhookSample = new DiscordWebhookBuilder
{
Username = "Username",
Content = "Message to Delete",
};
//Here I am getting the bot's main webhook in the current channel
DiscordWebhook currentChannelWebhook = await ctx.Channel.CreateWebhookAsync("Sample");
//Here I make the Webhook send a message and save the value
Task<DiscordMessage> result = await currentChannelWebhook.ExecuteAsync(WebhookSample);
//And finally, I delete the message sent
await result.DeleteAsync();

Related

Can I verify if message is sent successfully using Response<SendReceipt> in Azure Storage Queue

I am using the Azure Storage Queue Client to send base 64 encoded string messages. A very straight forward usage. I have the following code snippet:
var options = new QueueClientOptions
{
MessageEncoding = QueueMessageEncoding.Base64
};
var _queueClient = new QueueClient(settings.Value.ConnectionString, settings.Value.Name, options);
var message = JsonConvert.SerializeObject(messageObject, jsonSetting);
_queueClient.SendMessageAsync(message);
I know that SendMessageAsync( . . .) returns Response<SendReceipt> how do I use that to verify if a message is sent successfully or not ?
SendReceipt has MessageId and InsetionTime properties but the documentation does not specify what happens to these properties if message does not get sent. Does the queue simply returns null receipt or an object with default values ?
When you try to send a message to a queue using SendMessageAsync and if for some reason message is not sent, an exception is raised. You will not receive anything in the Response<SendReceipt>.
You will need to wrap your await _queueClient.SendMessageAsync(message); in a try/catch block. If no exception is raised that would mean the message is sent successfully.

Sending an HTML attachment from a Microsoft Teams bot

I'm working on a Teams bot and I'm trying various ways to send rich messages to users (we need clickable buttons) from my bot. I have tried adaptive cards, which are almost perfect, but noticed that on the toast popup for the message it just says "Testbot sent a card". This isn't ideal as we'd like an overview of the message to appear instead.
I noticed that when you use the weather app to send a card to another user, it has the desired effect- a short summary of the weather appears in the toast popup. Looking inside the JSON that represents that message shows that the "card" is actually an HTML attachment.
Am I able to replicate this by sending an HTML attachment? I have (naively) tried the following but it causes an exception:
Activity reply = new Activity();
reply.Type = ActivityTypes.Message;
reply.Text = "Test the toast";
reply.Conversation = new ConversationAccount()
{
Id = conversationResponse.Id
};
reply.Attachments.Add(new Attachment()
{
ContentType = "text/html",
Content = "<div>Some generated html</div>"
});
Am I just barking up the wrong tree completely?
Thanks.
Edit:
The exception I'm getting is "Operation returned an invalid status code 'BadRequest'" from within mscorlib.dll.
For an adaptive card, I can do the following, and it works fine:
reply.Attachments.Add(new Attachment()
{
ContentType = "application/vnd.microsoft.card.adaptive",
Content = JsonConvert.DeserializeObject("{Some generated JSON}")
});
When trying to send the attachment as HTML, I assume I need to do more than simply send a string as Content. I tried rendering an adaptive card to HTML and attaching the resultant RenderedAdaptiveCard object, but still got the same exception.
--
Edit 2:
When a colleague sends me a card using the weather app:
https://i.imgur.com/BlBk557.png
I get the following toast:
https://i.imgur.com/EoO8COj.png
When using that tool to send a message to the bot, I can see a message with an attachment of type text/html.
I was attempting to replicate this by sending a message from the bot to a user with an attachment of type text/html and some HTML in the content field. I now see that when I do this there is a 400 response from the serviceUrl which says
{"error":{"code":"BadArgument","message":"Unknown attachment type"}}
I think maybe the assumption I made was based on a misunderstanding. I take it that we can't have informative text on the toast for a card in the same manner as the weather app?
It seems like this is impossible. See comment on OP:
"Bots does not support an Html Attachment" - Gousia-MSFT

Notification Hub Delivery failure C#

I have two notification hub clients (nodejs and C#), both used for pushing messages into a hub.
The Node client sends perfectly fine, yet the C# client completes with no message being sent.
Below are the snippets for the used in each client.
C#
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<Connection String>", "<Hub Name>");
var notice = #"{'aps':{'alert':'Notification Hub test notification'}}";
var result = await hub.SendAppleNativeNotificationAsync(notice, "<tag>");
Console.WriteLine(result.State);
NodeJS
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('<Hub Name>','<Connection String>')
var notice = "{'aps':{'alert':'Notification Hub test notification'}}"
notificationHubService.apns.send("<tag>", notice, function(error, res){
console.log(res);
});
Both work fine when sending Android notifications and messages sent directly from the Azure portal Test feature are fine.
Any assistance would be greatly appreciated.
Duncan,
I think the issue is because your payload is malformed as you are using single quotes. Try the following:
var notice = "{\"aps\":{\"alert\":\"Notification Hub test notification\"}}";
You can try to use the EnableTestSend feature and look at the NotificationOutcome property for the detailed error message. This will send a test send message to 10 devices.
bool enableTestSend = true;
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(connString, hubName, enableTestSend);
var outcome = await hub.SendWindowsNativeNotificationAsync(toast);
Console.WriteLine(outcome.State);
foreach (RegistrationResult result in outcome.Results)
{
Console.WriteLine(result.ApplicationPlatform + "\n" + result.RegistrationId + "\n" + result.Outcome);
}
TLDR - No '' (single quotes) allowed! Payload must containt alert key
Not a very exciting solution but...
If the notification payload contains single quotes even in a string literal the Notification hub will en-queue it without a malformed exception but when it reaches the APNS it will not be delivered as the payload is invalid according to them.
If the notification payload doesn't have alert key present it will also be en-queued but not delivered by the APNS
As already mentioned in my colleagues answers, you need to use double quotes in C# as a first step.
Second, you also need to escape the json characters:
Your payload should look like this:
var notice = "{{\"aps\":{{\"alert\":\"Notification Hub test notification\"}}}}";
Basically you escape the json braces { } by adding additional ones {{ }}.
This will send a valid json payload to the SendAppleNativeNotificationAsync() method. The payload now sent looks like this:
{"aps":{"alert":"Notification Hub test notification"}} (which is the correct notification format on iOS)
Here are the valid json payloads for iOS from the Apple Developer webpage.
You could always test if the json you are sending is a valid notification payload by using the 'Test Send' functionality in the Azure Notification Hub you are using.

Telegram C# example send message

I can't find an example of sending message by telegram protocol from C#. I tried to use this but failed.
Can you give me any examples?
TLSharp is basic implementation of Telegram API on C#. See it here https://github.com/sochix/TLSharp
You can use the WTelegramClient library to connect to Telegram Client API protocol (as a user, not a bot)
The library is very complete but also very easy to use. Follow the README on GitHub for an easy introduction.
To send a message to someone can be as simple as:
using TL;
using var client = new WTelegram.Client(); // or Client(Environment.GetEnvironmentVariable)
await client.LoginUserIfNeeded();
var result = await client.Contacts_ResolveUsername("USERNAME");
await client.SendMessageAsync(result.User, "Hello");
//or by phone number:
//var result = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = "+PHONENUMBER" } });
//client.SendMessageAsync(result.users[result.imported[0].user_id], "Hello");
For my bot I use Telegram.Bot nuget package. Full sample code is here.
Here is example of sending message in reply to incoming message.
// create bot instance
var bot = new TelegramBotClient("YourApiToken");
// test your api configured correctly
var me = await bot.GetMeAsync();
Console.WriteLine($"{me.Username} started");
// start listening for incoming messages
while (true)
{
//get incoming messages
var updates = await bot.GetUpdatesAsync(offset);
foreach (var update in updates)
{
// send response to incoming message
await bot.SendTextMessageAsync(message.Chat.Id,"The Matrix has you...");
}
}
The simplest way is to send http request directly to the Telegram BOT API as url string, you may test those url strings even in your browser, please see details in my another answer here:
https://stackoverflow.com/a/57341990/11687179
at the first step you have to generate a bot in botfather then use the code in bellow in C#
private void SendMessage(string msg)
{
string url = "https://api.telegram.org/{botid}:{botkey}/sendMessage?chat_id={#ChanalName}&text={0}";
WebClient Client = new WebClient();
/// If you need to use proxy
if (Program.UseProxy)
{
/// proxy elements are variable in Program.cs
Client.Proxy = new WebProxy(Program.ProxyUrl, Program.ProxyPort);
Client.Proxy.Credentials = new NetworkCredential("hjolany", "klojorasic");
}
Client.DownloadString(string.Format(url, msg));
}));
}
Telegram has an official API that can do exactly what you need, you will have to look into http requests though..
Here is the documentation on sending a message:
Function
messages.sendMessage
Params
peer InputPeer User or chat where a message will be sent
message string Message text
random_id long Unique client message ID required to prevent message resending
Query example
(messages.sendMessage (inputPeerSelf) "Hello, me!" 12345678901)
Return errors
Code Type Description
400 BAD_REQUEST PEER_ID_INVALID Invalid peer
400 BAD_REQUEST MESSAGE_EMPTY Empty or invalid UTF8 message was sent
400 BAD_REQUEST MESSAGE_TOO_LONG Message was too long.
Current maximum length is 4096 UTF8 characters
For the full documentation go here.

Getting the call response from the menu with Twilio

I am using C# to send a phone message with option(Twimlet) for the user to press 1 to confirm. How do I get the response from the call?
The code terminates prior to the call being placed, I assume I need to query the twilio server with the call sid?
static void Main(string[] args)
{
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var options = new CallOptions();
options.Url = "http://twimlets.com/menu?Message=Please%20press%201%20to%20confirm%20or%20Press%202%20to%20cancel&Options%5B1%5D=http%3A%2F%2Ftwimlets.com%2Fmessage%3FMessage%255B0%255D%3DYou%2520have%2520confirmed%252C%2520Thank%2520you%2520good%2520bye.%26&Options%5B2%5D=http%3A%2F%2Ftwimlets.com%2Fmessage%3FMessage%255B0%255D%3DYou%2520have%2520selected%2520to%2520cancel.%2520Thank%2520you.%2520Good%2520bye%26&";
options.To = "+13105551212";
options.From = "+13105551213";
var call = twilio.InitiateOutboundCall(options);
Console.WriteLine(call.Sid);
In order to respond to any input from the call, you need to use URLs under your control. Twimlets are pre-defined "apps" that don't give you control of the call flow outside of what you can specify in URL parameters.
The code you have now terminates because all it is doing is making an HTTP call to Twilio's servers telling it to start the call, with the options.Url endpoint responsible for handling that call's flow. To write a custom flow, you would need to create a public URL that returns TwiML for the desired flow.
Once you've got that going, you'll use the url attribute of the <Gather> verb to indicate where the key press data should be sent.

Categories