I'm trying to use message template for iOS - c#

I want to create template for push notification so far I'm stuck here and it's not working.
public static async void SendPushNotificationApns1(string msgTemplate)
{
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(ListenConnectionString, NotificationHubName);
string msg = "{\"aps\":{\"alert\":\"$(msgTemplate)\"}}";
await hub.SendAppleNativeNotificationAsync(msg);
}

It happened with: string msg = "{\"aps\":{\"alert\":\"" + $"{messageParam}" +"\"}}";

Related

Which way to use send messages into topic using azure function?

I found two ways to send messages into service bus topic from azure function.
one is using output -
[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string ServiceBusOutput([HttpTrigger] dynamic input, ILogger log)
{
log.LogInformation($"C# function processed: {input.Text}");
return input.Text;
}
Another is using code -
const string ServiceBusConnectionString = "string";
const string TopicName = "topicName";
static ITopicClient topicClient;
topicClient = new TopicClient(ServiceBusConnectionString, TopicName);
string messageBody = "Test";
var message = new Message(Encoding.UTF8.GetBytes(messageBody));
await topicClient.SendAsync(message);
I'm not getting which one we should use and when?
if we use Output how to pass queue name myqueue as a variable
so that in code we can assign it.
if i have array how can we return one by one message to output
return which will send one by one message to queue ?
Full examples from here. For instance, how to write multiple messages, using the ICollector
public static void Run(TimerInfo myTimer, ILogger log, [ServiceBus("myqueue", Connection = "ServiceBusConnection")] ICollector<string> outputSbQueue)
{
string message = $"Service Bus queue messages created at: {DateTime.Now}";
log.LogInformation(message);
outputSbQueue.Add("1 " + message);
outputSbQueue.Add("2 " + message);
}
As far as I know the first version, using return does not work if you have any async calls inside your Function. The version using the collector can also work in async Functions but simply using an IAsyncCollector instead.
if we use Output how to pass queue name myqueue as a variable
so that in code we can assign it.
For this you can use Imperative Binding.Imperative binding is useful when binding parameters need to be computed at runtime rather than design time. More reference here
Example:
public static async Task ServiceBusBinderTest(
string message,
int numMessages,
Binder binder) {
var attribute = new ServiceBusAttribute(BinderQueueName) {
EntityType = EntityType.Queue
};
var collector = await binder.BindAsync < IAsyncCollector < string >> (attribute);
for (int i = 0; i < numMessages; i++) {
await collector.AddAsync(message + i);
}
await collector.FlushAsync();
}
if i have array how can we return one by one message to output return which will send one by one message to queue ?
You can configure the OnMessageOptions instance with decreasing your MaxConcurrentCalls
OnMessageOptions options = new OnMessageOptions();
options.AutoComplete = false;
options.MaxConcurrentCalls = 5;

Message not sending to Azure Events Hub: Put token failed. status-code: 404, status-description: The messaging entity... ...could not be found

I am learning Azure Events Hub. A simple application i have downloaded from this link https://learn.microsoft.com/en-us/azure/event-hubs/event-hubs-dotnet-standard-getstarted-send . But when i try to send message, its giving me this error:
10/23/2018 11:11:13 PM > Exception: Put token failed. status-code:
404, status-description: The messaging entity
'sb://demo.servicebus.windows.net/myTeam' could not
be found. TrackingId:[My Tracking ID],
SystemTracker:iot-bd-madness.servicebus.windows.net:IoT-BD-Madness,
Timestamp:10/23/2018 5:11:18 PM.
In Azure Event Hub Dashboard all incoming requests (sending from console app) are visible with chart. but those are all request actually failed when i tried in console application
N.B:the given connectionstring is not real
public class Program
{
private static EventHubClient eventHubClient;
private const string EventHubConnectionString = "Endpoint=sb://iot-bd-madness.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
private const string EventHubName = "Iot-Bd-Madness";
public static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
private static async Task MainAsync(string[] args)
{
// Creates an EventHubsConnectionStringBuilder object from a the connection string, and sets the EntityPath.
// Typically the connection string should have the Entity Path in it, but for the sake of this simple scenario
// we are using the connection string from the namespace.
var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
{
EntityPath = EventHubName
};
eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
await SendMessagesToEventHub(100);
await eventHubClient.CloseAsync();
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
// Creates an Event Hub client and sends 100 messages to the event hub.
private static async Task SendMessagesToEventHub(int numMessagesToSend)
{
for (var i = 0; i < numMessagesToSend; i++)
{
try
{
var message = $"Message {i}";
Console.WriteLine($"Sending message: {message}");
await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));
}
catch (Exception exception)
{
Console.WriteLine($"{DateTime.Now} > Exception: {exception.Message}");
}
await Task.Delay(10);
}
Console.WriteLine($"{numMessagesToSend} messages sent.");
}
}
}
I ran into same problem. My EventHubName = "myeventhubname" was wrong. I passed the Event Hubs Namespace value - rounded in red. It gave error.
I changed it to value under Event Hub page left column -> click Entities -> Event Hubs
I used the name that was shown in the table rounded in green.

Discord.NET C# Change Content of SocketMessage

So I am listening to the event whenever anyone on the server sends a message to any text channel with my bot. I want to detect swear words like "fuck" and change it to "f*ck".
I was unable to replace my message just normally only with reflection but it did not help since it only replaced it in the instance of the SocketMessage but it did not change the message on the server.
Any solution for that?
Framework: 4.6
Discord.NET: 1.0.2
Code:
private async Task MsgRec(SocketMessage e)
{
try
{
if (e.Content.Contains("fuck"))
{
foreach(PropertyInfo info in typeof(SocketMessage).GetProperties())
{
if (info.Name == "Content")
{
info.SetValue(e,e.Content.Replace("fuck", "f*ck"));
}
}
}
}
catch (Exception ex)
{
await e.Author.SendMessageAsync(ex.StackTrace);
}
}
Update I also tried this without any success:
var rMessage = (RestUserMessage) await e.Channel.GetMessageAsync(e.Id);
await rMessage.ModifyAsync(msg => msg.Content = e.Content.Replace("fuck", "f*ck"));
Discord, like other chat programs, does not allow you to change messages of users. You can not censor what a user wrote, you can only delete the whole message.
maybe you could try something like this
private async Task MsgRec(SocketMessage e)
{
var msg = e as SocketUserMessage;
if (msg == null) return;
if (msg.Content.Contains("fuck"))
{
var newMsg = msg.Content.Replace("fuck", "f*ck");
await Context.Channel.SendMessageAsync(newMsg);
}
}

Microsoft bot framework webchat C#

I am developing a chatbot using the Microsoft bot framework in C#. We have a functionality where it queries the database and returns the result, but it might take up to 25-30 secs for the result to return.
By that time bot says "cannot send,please retry". Is there a way to increase this timeout? Or can we have something like "please wait" message for the user so that user will know that the request is processing?
It's hard coded in SDK, we're not able to override the message like "Couldn't send, retry". As Nicolas said, a workaround is to send a proactive message to user.
For example you can firstly create a ConversationStarter.cs class like this:
public class ConversationStarter
{
//Note: Of course you don't want these here. Eventually you will need to save these in some table
//Having them here as static variables means we can only remember one user :)
public static string fromId;
public static string fromName;
public static string toId;
public static string toName;
public static string serviceUrl;
public static string channelId;
public static string conversationId;
//This will send an adhoc message to the user
public static async Task Resume(string conversationId, string channelId)
{
var userAccount = new ChannelAccount(toId, toName);
var botAccount = new ChannelAccount(fromId, fromName);
var connector = new ConnectorClient(new Uri(serviceUrl));
IMessageActivity message = Activity.CreateMessageActivity();
if (!string.IsNullOrEmpty(conversationId) && !string.IsNullOrEmpty(channelId))
{
message.ChannelId = channelId;
}
else
{
conversationId = (await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount)).Id;
}
message.From = botAccount;
message.Recipient = userAccount;
message.Conversation = new ConversationAccount(id: conversationId);
message.Text = "Hello, work is done!";
message.Locale = "en-Us";
await connector.Conversations.SendToConversationAsync((Activity)message);
}
}
Then in your dialog, you can code like this:
public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
//We need to keep this data so we know who to send the message to. Assume this would be stored somewhere, e.g. an Azure Table
ConversationStarter.toId = message.From.Id;
ConversationStarter.toName = message.From.Name;
ConversationStarter.fromId = message.Recipient.Id;
ConversationStarter.fromName = message.Recipient.Name;
ConversationStarter.serviceUrl = message.ServiceUrl;
ConversationStarter.channelId = message.ChannelId;
ConversationStarter.conversationId = message.Conversation.Id;
await context.PostAsync("Please wait, we're processing...");
Processing();
}
public async Task Processing()
{
//replace the task.delay() method with your task.
await Task.Delay(30000).ContinueWith((t) =>
{
ConversationStarter.Resume(ConversationStarter.conversationId, ConversationStarter.channelId);
});
}
Then Task.Delay(30000) method is used for a 30s task testing, you should be able to replace it with your task for retrieving data from your database.
You should do the following:
acknowledge the request of the user with a basic text reply
save the message information and process the request
make a proactive message once you got the reply of your system

How to use Telegram API in C# to send a message

I want use Telegram API in C# for send a simple message to a number. I found some lib's on GitHub but I am not able to use them.
Can anyone give a simple code ? Can I simply make HTTP calls ?
Install-Package Telegram.Bot
Create a bot using the botfather
get the api key using the /token command (still in botfather)
use this code:
var bot = new Api("your api key here");
var t = await bot.SendTextMessage("#channelname or chat_id", "text message");
You can now pass a channel username (in the format #channelusername)
in the place of chat_id in all methods (and instead of from_chat_id in
forwardMessage). For this to work, the bot must be an administrator in
the channel.
https://core.telegram.org/bots/api
Here is the easiest way I found so far. I found it here, thanks to Paolo Montalto https://medium.com/#xabaras/sending-a-message-to-a-telegram-channel-the-easy-way-eb0a0b32968
After creating a Telegram bot via BotFather and getting your destination IDs
via https://api.telegram.org/bot[YourApiToken]/getUpdates
you can send a message to your IDs by issuing an HTTP GET request to Telegram BOT API using the following URL https://api.telegram.org/bot[YourApiToken]/sendMessage?chat_id=[DestitationID]&text=[MESSAGE_TEXT]
Details on a simple way to create a bot and get IDs may be found here: https://programmingistheway.wordpress.com/2015/12/03/send-telegram-messages-from-c/
You can test those url strings even directly in browser.
Here is a simple method I use in C# to send messages, without dependency on any bot api related dll and async calls complication:
using System.Net;
...
public string TelegramSendMessage(string apilToken, string destID, string text)
{
string urlString = $"https://api.telegram.org/bot{apilToken}/sendMessage?chat_id={destID}&text={text}";
WebClient webclient = new WebClient();
return webclient.DownloadString(urlString);
}
use this code :)
with https://github.com/sochix/TLSharp
using TeleSharp.TL;
using TLSharp;
using TLSharp.Core;
namespace TelegramSend
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TelegramClient client;
private async void button1_Click(object sender, EventArgs e)
{
client = new TelegramClient(<your api_id>, <your api_key>);
await client.ConnectAsync();
}
string hash;
private async void button2_Click(object sender, EventArgs e)
{
hash = await client.SendCodeRequestAsync(textBox1.Text);
//var code = "<code_from_telegram>"; // you can change code in debugger
}
private async void button3_Click(object sender, EventArgs e)
{
var user = await client.MakeAuthAsync(textBox1.Text, hash, textBox2.Text);
}
private async void button4_Click(object sender, EventArgs e)
{
//get available contacts
var result = await client.GetContactsAsync();
//find recipient in contacts
var user = result.users.lists
.Where(x => x.GetType() == typeof(TLUser))
.Cast<TLUser>()
.Where(x => x.first_name == "ZRX");
if (user.ToList().Count != 0)
{
foreach (var u in user)
{
if (u.phone.Contains("3965604"))
{
//send message
await client.SendMessageAsync(new TLInputPeerUser() { user_id = u.id }, textBox3.Text);
}
}
}
}
}}
There is now WTelegramClient, using the latest Telegram Client API protocol (connecting as a user, not 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");
1-first create a channel in telegram (for example #mychanel)
2-create a telegram bot (for example #myTestBot) and get api token for next step
3-add #myTestBot to your channel(#mychanel) as administrator user
4-use below code for send message:
var bot = new TelegramBotClient("api_token_bot");
var s = await bot.SendTextMessageAsync("#mychanel", "your_message");
this code work for me:
using System.Net;
public class TelegramBot
{
static readonly string token = "123456789:AAHsxzvZLfFAsfAY3f78b8t6MXw3";
static readonly string chatId = "123456789";
public static string SendMessage(string message)
{
string retval = string.Empty;
string url = $"https://api.telegram.org/bot{token}/sendMessage?chat_id={chatId}&text={message}";
using(var webClient = new WebClient())
{
retval = webClient.DownloadString(url);
}
return retval;
}
}
I've written a client library for accessing Telegram bot's API and its source code is available in the Github. You can browse to the Telebot.cs file to see a sample of how to send a message to the bot API.
Github URL: github.com/mrtaikandi/Telebot
Nuget URL: nuget.org/packages/Telebot
Same unexplicable errors.
Solution: elevate the framework dastination to minimum 4.6; errors disappear.
Perhaps official support pages at
https://telegrambots.github.io/book/1/quickstart.html
are a little bit confusing saying: "...a .NET project targeting versions 4.5+"
bye
Just look and learn how to make a POST HTTP request with your favorite language.
Then learn how to use Telegram Bot API with the documentation:
https://core.telegram.org/bots
https://core.telegram.org/bots/api

Categories