问题
I want mention users even those which do not have a username.
If a user has set up a username I return
Hi @username
as an answer but if a user does not have one I can't do that.
I tried using the unique User ID e.g.
@5642166
but that did not work.
How can I achieve that?
回答1:
According to official documentation it is possible to mention user by its numerical id with markup:
Markdown style
To use this mode, pass Markdown in the
parse_mode
field when usingsendMessage
. Use the following syntax in your message:
[inline mention of a user](tg://user?id=123456789)
and you can also use HTML
style :
HTML style
To use this mode, pass HTML in the parse_mode field when using sendMessage. The following tags are currently supported:
<a href="tg://user?id=123456789">inline mention of a user</a>
回答2:
Before I give you an answer I really suggest that you use the first_name attribute of an user. A username is not required if you have a Telegram account, but you have to enter a name.
Here is a code example of how I got the first_name attribute of a user:
$rawContent = file_get_contents("php://input");
$rawContentArray = json_decode($rawContent, true);
foreach ($rawContentArray as $key => $value) {
if($key === "message"){
foreach ($value as $messagekey => $messagevalue) {
if($messagekey === "chat"){
foreach ($messagevalue as $chatkey => $chatvalue) {
if($chatkey === "first_name"){
$first_name = $chatvalue;
}
}
}
}
}
}
If you want to get the username you can do the same, just replace first_name with username and add a simple check after you give $user_name a value:
if($user_name !== ''){
$user_name = "@undefined"}
The problem here is that you have to give a user a placeholder or generic username which is kind of stupid when you think about it. You are giving someone who is using your bot a name. Why do that? But if that's what you want, replace my "@undefined" with your placeholder.
来源:https://stackoverflow.com/questions/40905948/how-can-i-mention-telegram-users-without-a-username