Created a bot and group. Added bot to the group(as admin) and starting trying posts. Through Url, it's smooth and successful. Started off exploring Telegram API(JAVA). Tests were on getUpdate and sendMessage methods.
I have generated TOKEN from telegram webapp(https://web.telegram.org).
Code snippet to getUpdates: yes, I have included bot ahead of the token.
TelegramBot bot = new TelegramBot("BOT_TOKEN");
GetUpdates getUpdates = new GetUpdates().limit(100).offset(0).timeout(0);
GetUpdatesResponse gur = bot.execute(getUpdates);
List<Update> list = gur.updates();
for(Update update : list) {
System.out.println(update.message());
}
Resonse is null.
code for sendMessage:
SendMessage request = new SendMessage(chatId, text)
.parseMode(ParseMode.HTML)
.disableWebPagePreview(true)
.disableNotification(true)
.replyToMessageId(1)
.replyMarkup(new ForceReply());
// sync
SendResponse sendResponse = bot.execute(request);
boolean ok = sendResponse.isOk();
Message message = sendResponse.message();
System.out.println(ok);
System.out.println(message);
Response is false and null.
I'm referring https://github.com/pengrad/java-telegram-bot-api#send-message
Help me understand the mistake. Thanks.
You need 109780439:AAJqs_w-4 format token, for instance:
TelegramBot bot = new TelegramBot("109780439:AAJqs_w-4");
This token can be obtained from #BotFather.
Related
I am currently working on delivering 1:1 messages to the users in Teams.
Problem Statement: I am having trouble trying to get the member details to populate the Channel Account to set the ConverstationParameters object to create conversation if the user is not part of a team. Is there a way I could get the details of the user without having the user part of a Team. I wasn't able to find any reference documentation to how to get this information for Java.
Below is my code snippet:
Setup credentials and initialize a connection using Connector Client.
Populate Channel account with recipient details for set members on Conversation Parameters Object.
Activity message = MessageFactory.text("Hello World");
MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(appClientID, appClientSecret);
try (ConnectorClient client = new RestConnectorClient(serviceUrl, credentials)) {
logger.info("** Connector Client Set: {} **", client);
ConversationParameters conversationParameters = new ConversationParameters();
conversationParameters.setIsGroup(false);
CompletableFuture<ChannelAccount> user = ((Conversations) client.getConversations())
.getConversationMember(recipient, teamsInternalId); // Don't want to use this because the user has to be part of the same team which is not true in our case.
logger.info("** Aysnc get User details call **");
logger.info("** AAID: {} **", user.get().getAadObjectId());
try {
conversationParameters.setMembers(Collections.singletonList(user.get()));
} catch (ErrorResponseException e) {
logger.error("** User Error : {}**", e.getMessage());
}
conversationParameters.setTenantId(tenantId);
TenantInfo tenantInfo = new TenantInfo(tenantId);
TeamsChannelData channelData = new TeamsChannelData();
channelData.setTenant(tenantInfo);
conversationParameters.setChannelData(channelData);
CompletableFuture<ConversationResourceResponse> conversationResourceResponse = new CompletableFuture<ConversationResourceResponse>();
try {
conversationResourceResponse = client.getConversations()
.createConversation(conversationParameters);
logger.info("** Create Conversation: {} **", conversationResourceResponse.get().getId());
} catch (ErrorResponseException e) {
logger.error("** Create Conversation : {} **", e.getMessage());
}
CompletableFuture<ResourceResponse> response = client.getConversations()
.sendToConversation(conversationResourceResponse.get().getId(), message);
logger.info("** Send Conversation **", response.get().getId());
I solved the above requirement following these steps:
Check if my app is installed for the user using Graph API.
If not installed, force install the app for the user using Graph API.
Then retrieve the conversation chat id.
Use this chat id to send the message to the user.
There steps are outline here on the MSFT reference page:
https://learn.microsoft.com/en-us/microsoftteams/platform/graph-api/proactive-bots-and-messages/graph-proactive-bots-and-messages?tabs=dotnet
I hope this answer helps anyone in the same boat who would like to send messages directly 1:1 from an app to a Teams user without any mutual Team condition.
I have two Telegram bots, written in Java.
First bot send some message every 10 min. (It works).
Second bot must read this sended message, and store it to txt file...
But problem is that the second bot don't see this message... He see messages only from USERS.
M - bot
YR - user
Chat image
Console result
Here says if
BotFather=>Bot=>Settings=>Group Privacy => Privacy mode disabled and >BotFather=>Bot=>Settings=>Allow Groups? => Groups are currently enabled
bots must see messages sent from one to another.
I did it, also bots was invited to new group with Administrator rights. Here code example (second bot):
public class TelegramBot extends TelegramLongPollingBot {
public final String BOT_TOKEN = "****************************";
public final String BOT_NAME = "*****************";
#Override
public void onUpdateReceived(Update update) {
long inChatID = 0;
int inMessID = 0;
String inText = "";
try { // from chanel
inChatID = update.getChannelPost().getChatId();
inText = update.getChannelPost().getText();
inMessID = update.getChannelPost().getMessageId();
} catch (Throwable t1) {};
try { // from chat
inChatID = update.getMessage().getChatId();
inText = update.getMessage().getText();
inMessID = update.getMessage().getMessageId();
} catch (Throwable t2) {};
System.out.println(inChatID);
System.out.println(inMessID);
System.out.println(inText);
}
#Override
public String getBotUsername() {
return BOT_NAME;
}
#Override
public String getBotToken() {
return BOT_TOKEN;
}
}
If I send any message like user, i getting in console ChatID, MessID, Text...
But if first bot send some message, i got nothing. Help me with this issue. Any suggestion where my mistake ?
I solved this issue by adding this two bots to channel with administrator rights.
It's don't works with GROUP CHAT.
Now i can see message sended from another bots.
But there is another problem: all messages sended by any bot in channel throws like channel message, with out Bot ID, Bot Name, etc...
So, I just can read message text, and parse it.
I am trying to use telegram database library for java (tdlib or tdapi) but when i get chatId of a channel by SearchPublicChat and try to get messages or view messages i get an error.
Error{code=6 message= Chat not found}
I can not understand why the chatId i receive above why when i pass it to another method i get that error
Please help me about that problem and that library.
Thank you.
example for getting last 15 messages from chat
String username = "any_chat_public_link";
TdApi.SearchPublicChat searchPublicChat=new TdApi.SearchPublicChat(username);
TG.getClientInstance().send(searchPublicChat, new Client.ResultHandler() {
#Override
public void onResult(TdApi.TLObject object) {
TdApi.Chat chat = (TdApi.Chat) object;
TdApi.Message topMessage = chat.topMessage;
long chatId = chat.id;
TdApi.GetChatHistory getChatHistory = new TdApi.GetChatHistory(chatId, topMessage.id, 0, 15);
TG.getClientInstance().send(getChatHistory, new Client.ResultHandler() {
#Override
public void onResult(TdApi.TLObject object) {
TdApi.Messages messages = (TdApi.Messages) object;
}
});
}
});
Before requesting chat by id the TdLib must know about this chat in current session. You need search this chat by #mention_link if it public, or getting whole your chat list. Also, the library will be know about chat if some action happens with this chat (like new message from chat, chat updated...)
And this applies also to messages, users and etc. You can request it by id only when TdLib know about this entity.
Before receiving the message history, you need to subscribe to the chat by sending TdApi.JoinChat. The procedure is as follows:
1) TdApi.SearchPublicChat
2) TdApi.JoinChat
3) TdApi.GetChatHistory
TdApi.GetChatHistory requires the id of the last chat message. It can be obtained using the TdApi.GetChat method.
I used tdlib/example. Information about chats is updated automatically by the getMainChatList method, then it can be obtained from chats.get(chatId)
I am sending push notifications using UrbanAirship API using java.
Here is the doc: http://docs.urbanairship.com/api/
I want to send a push notifications with custom key/value. For example, I want send to following to Android/iOS device
name: "Jack"
String appKey = "appKey";
String appSecret = "appSecret";
// Setup an authenticated APIClient with your application key and
// application master secret.
APIClient apiClient = APIClient.newBuilder()
.setKey(appKey)
.setSecret(appSecret)
.build();
// Setup a push payload to send to the API with our handy builders
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.all())
.setNotification(Notifications.notification("UA Push"))
.setDeviceTypes(DeviceTypeData.of(DeviceType.IOS))
.build();
// Try and send, handle anything that comes up
try {
APIClientResponse<APIPushResponse> response = apiClient.push(payload);
logger.info("Sent a push message!");
}
// Non 200 responses throw an APIRequestException. Check the documentation
// to debug your request.
catch (APIRequestException ex){
logger.error("Non 200 request, checking error details and taking action");
}
// An underlying error occurred, most likely outside of the scope of the
// UA library, do some HTTP debugging
catch (IOException e){
logger.error("Broken pipe what?");
}
Here is the code reference for android - https://github.com/urbanairship/java-library/blob/master/src/test/java/com/urbanairship/api/push/model/notification/android/AndroidDevicePayloadTest.java
How can i do send push notification with custom key/value using AndroidDevicePayload ?
You can create your notification like this:
public PushPayload createPushPayloadCustom(String namedUser, String message) {
Notification notification = Notification.newBuilder()
.addDeviceTypeOverride(DeviceType.IOS, IOSDevicePayload.newBuilder()
.setAlert(message)
.build())
.addDeviceTypeOverride(DeviceType.ANDROID, AndroidDevicePayload.newBuilder()
.setAlert(message)
.build())
.build();
return PushPayload.newBuilder()
.setAudience(Selectors.namedUser(namedUser))
.setNotification(notification)
.setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
.build();
}
You can add to the "extras" object any key/value:
DeviceTypeData deviceTypeData = DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID);
IOSDevicePayload iosPayload = IOSDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_ios_key", "custom value for IOS")
.build();
AndroidDevicePayload androidPayload = AndroidDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_android_key", "custom value for Android")
.build();
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.namedUser(email))
.setNotification(Notifications.notification(iosPayload,androidPayload))
.setDeviceTypes(deviceTypeData)
.build();
Then in the received push, you will find the object:
For more details go to urbanairship official documentation
I'm trying to send a notification to my pebble watch. I'm using this code, which is basically the example from the website:
public void sendPebble(String title, String body) {
final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION");
final Map<String, String> data = new HashMap<String, String>();
data.put("title", title);
data.put("body", body);
final JSONObject jsonData = new JSONObject(data);
final String notificationData = new JSONArray().put(jsonData).toString();
i.putExtra("messageType", "PEBBLE_ALERT");
i.putExtra("sender", "Test");
i.putExtra("notificationData", notificationData);
Log.d("Test", "Sending to Pebble: " + notificationData);
sendBroadcast(i);
}
I'm getting the message in LogCat, but no notification on the watch. The procedure seems simple enough, is there something too obvious I missed? Or is the documentation just incomplete?
Edit: The obvious questions:
Yes, the watch is connected
Yes, I have third party notifications enabled
Okay, this was my problem:
By default the Pebble app only sends notifications to the watch while the screen of the phone is off. For development I always have the screen active while the phone is connected via USB. So, the solution was: Enable the "Always send Notifications" option in the Pebble app.
Maybe this spares someone else a headache.