I am student who is studying computer programming in Canada.
Nowadays , I am making the app as my side project with flutter/firebase.
In my app chat function is included. The problem that I am facing is how to increment badge number and keep it if the message is not read.
I attached the picture of my Message data structure in the firebase.
and below code is the firebase function code. For now I am pushing the notification with this code.
I am getting the notification successfully , but the problem is the how to count badge number of the app icon. As you can see in the notification badge number is '1'. Whenever I push the notification, that number is overriding previous number. I think this is wrong way, what I am expecting, if the value isMessageRead in the firebase database increment badge number. I am just wondering the logical way , or any other source that I can study that can explain how to count the Icon badge Number.
For now I have no idea how to manage badge number.
Thanks for reading,
I am waiting for your reply.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.onCreateMessage = functions.firestore.document('/Chat/{currentUserID}/UserList/{anotherUserID}/Messages/{message}')
.onCreate(async (snap, context) => {
const currentUserID = context.params.currentUserID;
const anotherUserID = context.params.anotherUserID;
console.log(currentUserID);
console.log(anotherUserID);
if (currentUserID == snap.data().recieverID) {
return admin.messaging().sendToTopic(`${currentUserID}`, {
notification: {
title: snap.data().senderID,
body: snap.data().message,
clickAction: 'FLUTTER_NOTIFICATION_CLICK',
sound: 'default',
badge: '1'
}
});
}
});
enter code here
For badge to do that manually you have to store user unread message count somewhere in firebase (recommend in user node.)So when user read or get messages then you need to update that count number
Here is a package that will help you show a badge on app icons.
flutter_app_badger
https://pub.dev/packages/flutter_app_badger
FlutterAppBadger that can you update your count on app icons. It supports Both IOS and Android like this.
FlutterAppBadger.updateBadgeCount(1);
Remove a badge
FlutterAppBadger.removeBadge();
I'm trying to display a local notification without a sound using react-native-firebase, is that possible?
I have tried playing around with the AndroidNotification class, but couldn't find a way to do this.
const notification = new firebase.notifications.Notification()
.setNotificationId("notificationId")
.setTitle("Title")
.setBody("Text")
.android.setBigText("Big Text")
.android.setColor("#f04e29")
.android.setAutoCancel(true)
.android.setOnlyAlertOnce(true)
.android.setChannelId("channel")
.android.setLargeIcon("ic_launcher")
.android.setSmallIcon("ic_notification");
firebase.notifications().displayNotification(notification);
I would like for the notification to be displayed without any noise at all.
From my own experience, two things have to be taken into account:
No setSound method must be called or no sound properties should be set
When developing for Android API level >=26, the Android Importance passed as third argument of the Channel method has to be set to Low, Min or None. Otherwise the default sound is played anyway. So an example of creating your Channel (e.g. in the componentDidMount of your App.tsx):
const channel = new firebase.notifications.Android.Channel(
"testNotification",
"Test Notification",
firebase.notifications.Android.Importance.Low
)
firebase.notifications().android.createChannel(channel);
And then showing a nonobtrusive notification:
const notification = new firebase.notifications.Notification()
.setTitle("My notification title")
.setBody("My notification body");
notification.android.setChannelId("testNotification");
firebase.notifications().displayNotification(notification);
So i am using Firebase for my project. And what is does is that every time a new record is added into a specific collection in Firestore, my Firebase Function will be triggered thus sending the push notification into the devices of users who are subscribe to a specific topic.
Here is the code that i used for Firebase Function:
exports.sendNotifications = functions.firestore
.document('notifications/{sessionId}').onCreate(async event => {
const newValue = event.data();
// Gets data from the new notification record in Firestore.
const topicId = newValue.topicId;
const themeId = newValue.themeId;
const colorId = newValue.colorId;
let lable = newValue.lable;
let header = newValue.header;
// Limit the number of characters for push notifications
if(header.length >= 50){
header = header.substring(0,47) + "...";
} if(lable.length >= 100){
lable = lable.substring(0,97) + "...";
}
// Set the message for the notification.
const payload = {
notification: {
title: header,
body: lable,
}
}
let options = {
priority: 'high'
};
// Sends the notification to the users subscribed to the said topic
return admin.messaging().sendToTopic(topicId, payload, options)
});
Since the Function triggers and sends push notifications to all my users subscribe to a topic at the same time. Is it possible for the device (the receiving end) to not show the notification sent by my Function up until a specific time comes?
Cause users of my Ionic app needs to choose what time of the day they will be receiving push notification from the cloud.
I am aware that in the Firebase console, you can send notifications manually using a form and set the time and date in where the notification will be sent, but this does not work on my favor since my users did not set the same time and date for notifications to be showing.
There is no "deliver the message at this time" API in Firebase Cloud Messaging. See FCM Schedule delivery date or time of push notification
There are two ways to reach your goal:
Only call FCM when you want the message to be delivered. This will require that you create a Cloud Function that runs at an interval, and then when it is called only delivers the messages for that interval.
Deliver the message as a data message, which your app handles. And then hold the message on the client, until it is ready to display to the user. See the Android documentation on creating a notification for more on that.
So I have a Status Dropdown on a fragment page (used to edit database entries) that I want to send an email notification when the entry changes from "Pending" to "Ready to Build".
I am using the following code:
var widgets = widget.parent.descendants;
var to = 'notifications#xxx.com';
var subject = 'New System Order: ' + widgets.ProjectName.value;
var msg = "A new order for [ " + widgets.ProjectName.value + " ] has been created for [ " + widgets.UsersPosition.value + " ]";
sendMessage(to, subject, msg);
You can see that I also have it pulling the Project Name/User Position in the subject/body of the email. These are Text Boxes on that Fragment page displaying the information from the entry.
All of these works great and exactly as desired when the Dropdown and the Text Boxes are all in the same panel. However, when I separate them into separate panels (for aesthetics) the system cannot find widgets.ProjectName.value or widgets.UsersPosition.value.
I'm assuming I just need to adjust the var widgets = widget.parent.descendants; line, but I don't know to what.
Any help would be greatly appreciated. Thank you.
So it looks like I just need to change widget.parent.descendants; to widget.root.descendants;
I would recommend you to use Model events instead.
App Maker will fire the 'onSave' event every time a record is modified.
Go to the 'Events' tab in the model editor, and add something like:
if (oldRecord.State == "Pending" && record.State == 'Ready to Build') {
sendEmail_();
}
You can learn more about model events here.
Regards,
Julian.-
I've been using telegram_bot, and trying to get groupChat id to send notifications to group chat, but don't know which methods I have to use for it.
For getting chat id I use to message.chat.id when the bot participated in the chat but which I have to use for getting group chat id can't find/
In order to get the group chat id, do as follows:
Add the Telegram BOT to the group.
Get the list of updates for your BOT:
https://api.telegram.org/bot<YourBOTToken>/getUpdates
Ex:
https://api.telegram.org/bot123456789:jbd78sadvbdy63d37gda37bd8/getUpdates
Look for the "chat" object:
{"update_id":8393,"message":{"message_id":3,"from":{"id":7474,"first_name":"AAA"},"chat":{"id":<group_ID>,"title":""},"date":25497,"new_chat_participant":{"id":71,"first_name":"NAME","username":"YOUR_BOT_NAME"}}}
This is a sample of the response when you add your BOT into a group.
Use the "id" of the "chat" object to send your messages.
(If you created the new group with the bot and you only get {"ok":true,"result":[]}, remove and add the bot again to the group)
Private chart only works in image argoprojlabs/argocd-notifications:v1.1.0 or above.
Here is the sequence that worked for me after struggling for several hours:
Assume the bot name is my_bot.
1- Add the bot to the group.
Go to the group, click on group name, click on Add members, in the searchbox search for your bot like this: #my_bot, select your bot and click add.
2- Send a dummy message to the bot. You can use this example: /my_id #my_bot
(I tried a few messages, not all the messages work. The example above works fine. Maybe the message should start with /)
3- Go to following url: https://api.telegram.org/botXXX:YYYY/getUpdates
replace XXX:YYYY with your bot token
4- Look for "chat":{"id":-zzzzzzzzzz,
-zzzzzzzzzz is your chat id (with the negative sign).
5- Testing: You can test sending a message to the group with a curl:
curl -X POST "https://api.telegram.org/botXXX:YYYY/sendMessage" -d "chat_id=-zzzzzzzzzz&text=my sample text"
If you miss step 2, there would be no update for the group you are looking for. Also if there are multiple groups, you can look for the group name in the response ("title":"group_name").
As of May 2021, simply:
Invite #RawDataBot to your group.
Upon joining it will output a JSON file where your chat id will be located at message.chat.id.
"message": {
"chat": {
"id": -210987654,
"title": ...,
"type": "group",
...
}
...
}
Be sure to kick #RawDataBot from your group afterwards.
After mid-2018:
1:) Invite #getidsbot or #RawDataBot to your group and get your group id from the chat id field.
Message
├ message_id: 338
├ from
┊ ├ id: *****
┊ ├ is_bot: false
┊ ├ first_name: 사이드
┊ ├ username: ******
┊ └ language_code: en
├ chat
┊ ├ id: -1001118554477 // This is Your Group id
┊ ├ title: Test Group
┊ └ type: supergroup
├ date: 1544948900
└ text: A
2:) use an unofficial Messenger like Plus Messenger and see your group id in group/channel info.
Before mid-2018: (don't Use)
1: Goto (https://web.telegram.org)
2: Goto your Gorup and Find your link of Gorup(https://web.telegram.org/#/im?p=g154513121)
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup
bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm
the simplest way i found using only telegram-web :
open web.telegram in browser ( chrome in my case )
right click on the group name on the left menu
click 'inspect' button
you will see the group id in the attribute
data-peer-id="-xxxxxxxxxx" or peer="-xxxxxxxxxx"
group chat id : -xxxxxxxxxx
channel chat id : -100xxxxxxxxxx
(for some channels/groups you need to add -100 prefix)
Edit :
in some cases the ID is shown in the browsers address bar when you click a group name
https://web.telegram.org/z/#-xxxxxxxxxx
You can get Chat ID in this way.
On private chat with your bot, send a random message. You will search this message later.
Get Your API-token from bot_father : XXXXXXXXX:YYYYYYY-YYYYYYYYYYYYYYYYY_YY
Then, on your browser make a request with that url :
https://api.telegram.org/botXXXXXXXXX:YYYYYYY-YYYYYYYYYYYYYYYYY_YY/getUpdates
The request returns a json response, in json text search your random message and get chat id in that object.
Using python and telethon it's very easy to get chat id. This solution is best for those who work with telegram API.
If you don't have telethon, run this:
pip install telethon
If you don't have a registered app with telegram, register one:
The link is this: https://my.telegram.org/
Then run the following code:
from telethon import InteractiveTelegramClient
from telethon.utils.tl_utils import get_display_name
client = InteractiveTelegramClient('session_id', 'YOUR_PHONE_NUMBER', api_id=1234YOURAPI_ID, api_hash='YOUR_API_HASH')
dialog_count = 10
dialogs, entities = client.get_dialogs(dialog_count)
for i, entity in enumerate(entities):
i += 1 # 1-based index
print('{}. {}. id: {}'.format(i, get_display_name(entity), entity.id))
You may want to send a message to your group so the group show up in top of the list.
You can retrieve the group ID the same way. It appears in the message body as message.chat.id and it's usually a negative number, where normal chats are positive.
Group IDs and Chat IDs can only be retrieved from a received message, there are no calls available to retrieve active groups etc. You have to remember the group ID when you receive the message and store it in cache or something similar.
My second Solution for the error {"ok":true,"result":[]}
Go in your Telegram Group
Add new User (Invite)
Search for "getidsbot" => #getidsbot
Message: /start#getidsbot
Now you see the ID. looks like 1068773197, which is -1001068773197 for bots (with -100 prefix)!!!
Kick the bot from the Group.
Now go to the Webbrowser an send this line (Test Message):
https://api.telegram.org/botAPITOKENNUMBER:APITOKENKEYHERE/sendmessage?chat_id=-100GROUPNUMBER&text=test
Edit the API Token and the Group-ID!
go on the group of choice
add #rose bot
type the command /id
type the command /id
create a bot, or if already created set as follows:
has access to messages
apparently, regardless of how old/new the Telegram group is:
add a bot to the group
remove bot from the group
add bot again to the group
create a script file and run getUpdates method
example:
var vApiTokenTelegram = "1234567890:???>yg5GeL5PuItAOEhvdcPPELAOCCy3jBo"; // #?????Bot API token
var vUrlTelegram = "https://api.telegram.org/bot" + vApiTokenTelegram;
function getUpdates() {
var response = UrlFetchApp.fetch(vUrlTelegram + "/getUpdates");
console.log(response.getContentText());
}
function shall log to the console the following:
[20-04-21 00:46:11:130 PDT] {"ok":true,"result":[{"update_id":81329501,
"message":{"message_id":975,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454914,"left_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"left_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}}},{"update_id":81329502,
"message":{"message_id":976,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454932,"new_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_members":[{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}]}}]}
Telegram group chat_id can be extracted from above message
"chat":{"id":-1001202656383,"title"
Group chat id should start with - (minus) is essential
This is wrong
10540154212
This is correct
-10540154212
You can get your id by sending a /start message to the bot userinfobot
Note: once u search for userinfobot in telegram u get many responses.
Makesure u choose the one with #bot tag
I tested now 4h but it dont work 2021 with the group-chat-id. All the time the error {"ok":true,"result":[]}
But now i found a Solution:
1:) install the "Plus Messenger" (https://play.google.com/store/apps/details?id=org.telegram.plus)
2:) go in the Group => Tap now on the "Group-Name" in the Head => Double Tap now on the Headline from the Group. A Info is comming: ID123456789 is copy in the clipboard
3:) go in the Group an paste the clipboard text. It´s you Groud-ID
4:) looks like 1068773197, which is -1001068773197 for bots (with -100 prefix)!!!
btw, you see the user-id too, on your profil.
5:) Now go to the Webbrowser an send this line (Test Message):
https://api.telegram.org/botAPITOKENNUMBER:APITOKENKEYHERE/sendmessage?chat_id=-100GROUPNUMBER&text=test
Edit the API Token and the Group-ID!
IMHO the best way to do this is using TeleThon, but given that the answer by apadana is outdated beyond repair, I will write the working solution here:
import os
import sys
from telethon import TelegramClient
from telethon.utils import get_display_name
import nest_asyncio
nest_asyncio.apply()
session_name = "<session_name>"
api_id = <api_id>
api_hash = "<api_hash>"
dialog_count = 10 # you may change this
if f"{session_name}.session" in os.listdir():
os.remove(f"{session_name}.session")
client = TelegramClient(session_name, api_id, api_hash)
async def main():
dialogs = await client.get_dialogs(dialog_count)
for dialog in dialogs:
print(get_display_name(dialog.entity), dialog.entity.id)
async with client:
client.loop.run_until_complete(main())
this snippet will give you the first 10 chats in your Telegram.
Assumptions:
you have telethon and nest_asyncio installed
you have api_id and api_hash from my.telegram.org
I don't understand why the most obvious (and probably the simplest) answer isn't here.
As you are writing a bot, you can get the id with these three simple lines:
bot.on('message', (msg) => {
console.log(msg)
})
Then just check the groupId from the console :D
And as you are probably trying to look the groupId to be able to send message to a group with your bot, the correct answer is probably this:
You don't use anymore the groupId. You use the group name (the one with https://t.me/careless_whisper) prefixed with #. And remember that your group has to be public. Source: Telegram API
So if your group name is careless_whisper the recipient will be #careless_whisper
I'd like to note very specific case made me monkey around it.
I've got the chat_id with above steps in the format like -1001379XXXXXX. So I just supposed the real id is 1001379XXXXXX, and left it in a such format to the grafana admin page. But in fact the id got this - as the integral part. If was really needed to be copied together with numbers.
function adminCheck( chat_id, name ) {
var bAdminCheck = false;
var contents = JSON.parse( getAdmin( chat_id ) );
var i = 0;
while( !bAdminCheck && (i < contents.result.length ) ) {
if( name == (contents.result[i].user.first_name + " " + contents.result[i].user.last_name) ) {
bAdminCheck = true;
}
i++;
}
return bAdminCheck;
}
If you are implementing your bot, keep stored a group name -> id table, and ask it with a command. Then you can also send per name.