i'm trying to send message to People user name for example my friends username is #...
but no thing happend
no Error
and no send
can i use this library ?
or just with tlsharp?
how can i found apiid and hashid for my bot?
using Telegram.Bot;
and
public partial class Form1 : Form
{
Telegram.Bot. TelegramBotClient bot = new TelegramBotClient("token");
Thread a;
public Form1()
{
InitializeComponent();
}
public void GetUpdates()
{
int offset = 0;
while (true)
{
Telegram.Bot.Types.Update[] updates =
bot.GetUpdatesAsync(offset).Result;
foreach (var update in updates)
{
offset = update.Id + 1;
if (update.Message == null)
continue;
var from = update.Message.From.FirstName;
var text = update.Message.Text;
string chatid = update.Message.Chat.Id;
string username = update.Message.From.Username;
// label1.BeginInvoke(delegate { label1.Text = label1.BeginInvoke(delegate { label1.Text = string.Format("sender:{0}\ntext:{1}\ncatid:{2}", from, text, chatid); }); });
// lblshow.Text = string.Format("sender:{0}\ntext:{1}\ncatid:{2}", from, text, chatid);
//label1.Text = string.Format("sender:{0}\ntext:{1}\ncatid:{2}", from, text, chatid);
this.BeginInvoke((System.Windows.Forms.MethodInvoker)delegate () {textBox1.Text = string.Format("sender:{0}\ntext:{1}\ncusername:{2}", from, text, username); });
bot.SendTextMessageAsync( chatid, "سلام بر شما");
//is this correct for send to people?
bot.SendTextMessageAsync("#Hoda.....", "hi");
}
}
you cant send message to user by user Name.telegram bot API only accept user Id. (except channels).
When you try to send messages to users you must know their chatID (chatID is a long number which is unique for every user in telegram and never changes while username can be changed) or you must have stored their chatIDs in a database or a file or ...
This means a user must have sent at least one message to your bot before this includes the /start command. Then your bot can find out their chatID and using that chatID, you can send whatever you want to that user unless he/she has blocked your bot by pressing Delete and Stop button when trying to delete the conversation between him/her and your bot.
You can but don't pass # symbol, If the username is #me pass "me" to SendTextMessageAsync without passing #.
Related
I'll send an adaptive card to the user with 2 actions, but when I select an action, a null string will be send to the server. Because of that the bot can't understand what the user wants.
As an extra check, I echo everything that the user sends to the bot. There is a null or empty check.
Here you've the conversation in Teams:
Here is the conversation in the emulator:
Here is my code to create the activity:
Activity activity = new Activity()
{
Attachments = new List<Attachment>()
{
new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = new AdaptiveCard("1.0")
{
Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = $"Lorem reminder",
Size = AdaptiveTextSize.Large
},
new AdaptiveTextBlock()
{
Text = $"Hi {userName},\r\nYou've missed some lorem ipsum dolor sit amet:\r\n- **consectetur:** Ut porttitor\r\nChoose an action from below to add them."
}
},
Actions = new List<AdaptiveAction>()
{
CreateCardAction("First action"),
CreateCardAction("Second action")
}
}
}
},
From = turnContext.Activity.Recipient,
Recipient = turnContext.Activity.From,
Type = "message",
Conversation = turnContext.Activity.Conversation
};
private AdaptiveAction CreateCardAction(string text)
{
return new AdaptiveSubmitAction()
{
Title = text,
Data = text
};
}
Using type imBack for the AdaptiveSubmitAction (like the suggested actions) don't work here. See screenshot from the emulator below.
If you run this locally, using NGrok, it's worth having a look at the payload in the ngrok inspector so that you see what's send back (http://localhost:4040/).
Essentially, "Data" is just an "object" type so that you can submit whatever you want on there. Let's say, for instance, that you want it to send back an "id" value - simple attach that as the "Data" property, like:
private AdaptiveAction CreateCardAction(string text, string id)
{
return new AdaptiveSubmitAction()
{
Title = text,
Data = id
};
}
Alternatively, it can be a more complex object, like:
public class Foo {
public string something { get; set; }
public string id{ get; set; }
}
private AdaptiveAction CreateCardAction(string text, Foo foo)
{
return new AdaptiveSubmitAction()
{
Title = text,
Data = foo
};
}
then when the message comes in, on your OnTurnAsync, you can check if the Turncontext.Activity.Value contains something.
Actually, it seems that Teams strips away plain string "Data" property (which works perfectly fine on DirectLine channel instead).
If you are able to replace the plain string by a JObject, the problem is solved. If - for any reason - you want your bot to act as a "bridge" and forward to Teams channel an AdaptiveCard with a plain string "Data" property coming from a different channel (i.e. DirectLine), than wrapping the "Data" string content in a JObject could save your day.
I'm trying to make telegram bot using talegram.bot library and i have a question about user messages: how can i make receiving message from user only after some text from bot? Here is example from BotFather
e.g. if user send message to bot-bot ignores the message text and responses like that, but if
user clicks on InlineKeyboardButton, bot sending to user message like "write your text", bot recieves that text and saves
I suggest to you use Telegram.dll library if you are a C# programmer and easily Define a sample IF operation like below code . you can control every thing if use the DLL file .
String Token = "399684XXX:AAH_NiVFXXXXX";
int ID=0;
while (true)
{
bot.update = "true";
ID = bot.chat_id;
if (bot.message_text=="/contact-us"){
bot.sendMessage.send(ID, "Email:name#website.com" + "\n" + "Website: www.website.com");
}
if (bot.message_text=="/apple")
{
bot.sendMessage.send(ID, "lap lap lap...");
}
else
{
bot.sendMessage.send(ID, "/contact-us" + "\n" + "/apple");
}
}
Good morning all,
First of all apologies for the somewhat generic title. If in the course of this message I can come up with something a little more detailed, I will certainly change it.
I am working on a project that will contain 3 programs. The purpose is to be able to send a notification to all clients connected. For this there is a server, client, and console program.
The message itself will be an RTF file, but the notification also requires a sending department (string), and a display timer (TimeSpan).
Most of the project is done. The logic is mostly complete, it is multithreaded, all the classes are ready, and most tests work.
The problem I am having is that the server seems to not receive the data from the console in the right order. Thereby causing all sorts of problems.
The process from console to server is as follows:
Console first selects all relevant information for the notification:
Users (List, gathered from LDAP)
Expiration date and time (DateTime)
Time before close is allowed (long, amount of ticks)
Department (string)
RTF file
The server is already active, and has a separate thread for the console connections
Console connects to server
Server creates a separate thread to handle the console connection
Console sends the username of the logged on user to the server
Server checks whether user is allowed to create notification (for now it will always return true)
Console sends all the relevant information in the following order:
MessageID (string)
RecipientCount (number of users, used to loop appropriately from server side)
Recipients (foreach loop of List)
Department (string)
VisibleTime (long)
Expiration (DateTime)
and finally RTF file
I have used System.Diagnostics.Trace to check whether all information is sent correctly, and in the right order. This all checks out. But the thing is that roughly 75% of the time the server side seems to receive the RTF file at the moment it should be receiving the visibleTime.
The code is as follows:
private void SendMessage()
{
SendToServer(Environment.UserName);
if (bool.Parse(ReadFromServer()))
{
// User is allowed, continue
string messageID = DateTime.Now.ToUniversalTime().Ticks.ToString();
SendToServer(messageID); // MessageID
string recipientCount = lvRecipients.Items.Count.ToString();
SendToServer(lvRecipients.Items.Count.ToString()); // Amount of recipients
foreach (string item in lvRecipients.Items) // Loop to send each recipient
{
SendToServer(item);
}
string department = TB_Department.Text;
SendToServer(department); // Send department string
string visibleTime = TimeSpan.FromSeconds(SLIDER_VisibleTime.Value).Ticks.ToString();
SendToServer(visibleTime); // Send message visibility time
string expiration = DateTime.Now.ToUniversalTime().AddMinutes(2).ToString();
SendToServer(expiration); //TODO add UI control for this
SendRTFToServer(); // Send RTF file
MessageBox.Show(
"Your designated MessageID is: " + messageID + Environment.NewLine +
"Message upload is succesful.",
"Complete",
MessageBoxButton.OK);
}
else
{
// User is not allowed. Report to user. Disconnect (will be managed by the finally block)
MessageBox.Show(
"You are not allowed to upload messages to the server.",
"Access denied",
MessageBoxButton.OK,
MessageBoxImage.Stop);
return;
}
}
private void SendToServer(string toSend)
{
StreamWriter writer = new StreamWriter(server.GetStream());
writer.WriteLine(toSend);
writer.Flush();
}
private void SendRTFToServer()
{
StreamReader rtfFile = new StreamReader(File.Open(RTFLocation, FileMode.Open, FileAccess.Read));
StreamWriter sw = new StreamWriter(server.GetStream());
sw.Write(rtfFile.ReadToEnd());
sw.Flush();
server.GetStream().Flush();
}
private string ReadFromServer()
{
server.GetStream().Flush();
StreamReader reader = new StreamReader(server.GetStream());
return reader.ReadLine();
}
And from the server:
private void Connect()
{
string username = ReadFromConsole();
if (IsUserAllowed(username)) // Receive username
SendToConsole(bool.TrueString); // Send confirmation
else
{
SendToConsole(bool.FalseString); // Send denial
console.Close();
return;
}
string messageID = ReadFromConsole(); // Receive MessageID
string recipientCount = ReadFromConsole();
int numOfRecipients = int.Parse(recipientCount); // Receive and parse number of recipients
List<string> recipients = new List<string>();
for (int i = 0; i < numOfRecipients; i++)
{
string recipient = ReadFromConsole();
recipients.Add(recipient); // Receive recipient, add to list (required for Message)
}
string department = ReadFromConsole(); // Receive department string
string visibleTime = ReadFromConsole();
string expiration = ReadFromConsole();
StoreRTF(messageID); // Receive and store RTF file
console.Close(); // Connection is done, close
Message message = new Message(messageID, department, recipients, visibleTime, expiration);
}
private void SendToConsole(string toSend)
{
// Open client stream, and write information to it.
StreamWriter writer = new StreamWriter(console.GetStream());
writer.WriteLine(toSend);
writer.Flush();
}
private string ReadFromConsole()
{
// Read information from client stream
StreamReader reader = new StreamReader(console.GetStream());
return reader.ReadLine();
}
private void StoreRTF(string messageID)
{
// Check/create folder for Message storage
string messageFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\BMNotify\";
if (!Directory.Exists(messageFolder))
Directory.CreateDirectory(messageFolder);
// Create file to store message in
Stream rtfFile = File.Create(messageFolder + messageID + ".rtf");
// Store information from stream, and close resources
console.GetStream().CopyTo(rtfFile);
rtfFile.Close();
rtfFile.Dispose();
}
And the message class:
public class Message
{
internal string messageID;
internal string department;
internal List<string> recipients;
internal TimeSpan visibleAtLeast;
internal DateTime messageExpiration;
private static List<Message> allMessages; // Will hold te collection of Message's
public Message(string _messageID, string _department, List<string> _recipients, string visibleTime, string expiration)
{
messageID = _messageID;
recipients = _recipients;
department = _department;
visibleAtLeast = TimeSpan.FromTicks(long.Parse(visibleTime));
messageExpiration = DateTime.Parse(expiration);
if (allMessages == null)
allMessages = new List<Message>(); // Initialize if required
allMessages.Add(this);
}
internal Stream GetRTF()
{
return File.Open
(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\BMNotify\" + messageID + ".rtf",
FileMode.Open,
FileAccess.Read,
FileShare.Read);
}
static public List<Message> AllMessages()
{
if (allMessages == null)
allMessages = new List<Message>(); // Initialize if required
return allMessages;
}
static public void RemoveMessage(Message message)
{
allMessages.Remove(message);
}
}
If anyone could shed any light on this, or tell me what I should change.. Or basically anything that could get me going again, I would be very grateful!
Your problem may stem from the fact that you're using a StreamReader to read data from the connection. Internally StreamReader buffers data it reads from the underlying Stream. You are creating a new StreamReader every time you attempt to read from the connection, and then discarding it once you've read a single line. In doing so, you're also discarding any data read from the connection that was buffered by the StreamReader (which may have constituted all or part of the following fields).
You should probably attempt to create a single StreamReader on the network stream, and use that same instance for all reads.
I am trying to delete message from inbox. Message doesn't have messageId(it's not gmail)
I've found in this topic the solution
MailSystem.Net Delete Message, IndexOnServer Property = 0
However it doesn't work for me.
The code below is simplifed the application works as MVVM light application.
This is how I get emails.
for (int i = 1; i <= mails.MessageCount; ++i)
{
Message msg = fetch.MessageObject(i);
MessageModel tmpMsg = new MessageModel() { messageType = MessageModel.MessageType.INBOX, UID = i, Date = msg.Date, Body = content, Title = msg.Subject, Sender = msg.From.Merged, Receiver = msg.To[0].Merged, IsEncrypted = isEncrypted };
tmpMsg.MessageWasDeleted += tmpMsg_MessageWasDeleted;
InboxMessages.Messages.Add(tmpMsg); //this is observable collection of MessageModel
}
I've tested this code and proper id is added to messageModel object.
Now when I want to delete the message I use this code in model:
var imapClient = new Imap4Client();
imapClient.BeginConnect(ConfigurationManager.AppSettings["mail_smtp_host"], ConfigurationManager.AppSettings["mail_smtp_login"], ConfigurationManager.AppSettings["mail_smtp_password"], new AsyncCallback((res) =>
{
imapClient.EndConnect(res);
//var box = imapClient.AllMailboxes["INBOX"] ;
var box = imapClient.SelectMailbox("INBOX");
Message email = box.Fetch.MessageObject(UID); //this is just to check if proper message is going to be deleted
box.UidDeleteMessage(UID, true);
if (MessageWasDeleted != null) MessageWasDeleted(this, new EventArgs());
}));
This method removes the message based on UID(at least it should do it) but it doesn't. There is no error nothing appears.
Where I could make an error? What's the proper way to delete message using ActiveUpMail?
I have create one web application where user can send friend request. If there are two users A and B. If A user send friend request to B then one pop up display's on B user dashboard. In that pop up box two buttons are there confirm or ignore.
If user click on confirm button then it takes some time to close that popup box. Because in backgroud it execute code for send email. Once email sent then that popup box close. So I want to close that popup box immediately after clicking on confirm button and then after send mail to that user.
Here is my code for accepting request and sending mail
#region dlUserFriendRequests_ItemCommand
protected void dlUserFriendRequests_ItemCommand(object source, DataListCommandEventArgs e)
{
HtmlTable objDataTable;
//Panel objDataTable;
switch (e.CommandName)
{
case "confirm":
RadioButtonList objRadioButtonList;
int intFriendRelationID = -1;
objRadioButtonList = (RadioButtonList)e.Item.FindControl("rblstFriends");
if (objRadioButtonList != null)
{
intFriendRelationID = UserManagementBL.AcceptUserFriendRequest(Convert.ToInt32(e.CommandArgument), this.LoginSessionDO.UserID, objRadioButtonList.SelectedItem.Text);
if (intFriendRelationID > 0)
{
int SentByUserID = Convert.ToInt32(e.CommandArgument);
DataTable dtbSenderdetails = null;
string SenderEmail = "";
dtbSenderdetails = UserManagementBL.GetUserDetails(SentByUserID);
if (dtbSenderdetails != null)
{
SenderEmail = dtbSenderdetails.Rows[0]["UserName"].ToString();
SendConfirmationMail(SenderEmail);
Response.Redirect("~/Dashboard/Dashboard.aspx",false);
//GetUserFriendRequests();
}
}
}
break;
case "Ignore":
int intFriendRequestID = -1;
intFriendRequestID = UserManagementBL.IgnoreUserFriendRequest(Convert.ToInt32(e.CommandArgument), this.LoginSessionDO.UserID);
GetUserFriendRequests();
break;
}
}
#endregion
#region Send confirmation mail
public void SendConfirmationMail(string email)
{
//DataTable dtblUserDetails = UserManagementBL.GetUserByUserName(email);
//if (dtblUserDetails != null)
//{
//int UserID = Convert.ToInt32(dtblUserDetails.Rows[0]["UserID"]);
//string FirstName = Convert.ToString(dtblUserDetails.Rows[0]["FirstName"]);
//string LastName = Convert.ToString(dtblUserDetails.Rows[0]["LastName"]);
string FirstName = this.LoginSessionDO.FirstName;
string LastName = this.LoginSessionDO.LastName;
var parameters = new System.Collections.Generic.Dictionary<string, string>();
parameters.Add("USER_NAME", string.Format("{0} {1}", FirstName, LastName));
parameters.Add("USER_IMAGE_URL", string.Format(SystemConfiguration.GetSiteURL() + "UserControls/UserPhoto.ashx?UserID={0}", this.LoginSessionDO.UserID));
string ToAddress = email;
string subject = FirstName + " " + LastName + " confirmed you as a friend on Lifetrons.";
CommonFunctions.CommonFunctions.SendEmail(SystemConfiguration.GetEmailSenderAddress(), ToAddress, subject, CommonFunctions.EmailTemplates.AcceptFriendRequest, parameters);
//}
}
#endregion
Here is my pop up box image
So how can I close that pop up box immediately after confirm button click? Is there any changes in my code?
You would do this in JavaScript. I assume you're already using AJAX to perform the Confirm action, otherwise it would just be reloading the page and your popup shouldn't be there anyway (since they're already confirmed?).
If you have jQuery on the frontend, you can use:
$('#confirm-box-id').hide();
Without jQuery, you could use:
document.getElementById('confirm-box-id').style.display = 'none';
Re-reading your message, it seems this is just a long running action. You should note that if you do hide this and don't show any indication of progress using the code above, for example, your user may navigate away or close the browser, which may cause the action to stop processing or be terminated forcefully server-side so the confirmation would never happen.