Where should I upload my telegram bot's code to run? - telegram

I know I create new bot, give it name, description from BotFather inside telegram
But this only adds the bot, when I modify my bot, code some functionality in python\lua\php etc - where should the code go and how telegram will know the behavior of my bot?
Who runs the new code, where should I upload my new additional code for my bot?
Does it go to telegram server and runs there on the cloud?
If so, how to upload it?

After you have setup your Bot's identity (#bot_name) with BotFather, the next step is to design the interaction/functions your Bot will perform.
Your bot code lives on YOUR server.
Requests from users interacting with your #bot_name will be routed from Telegram to your servers which ...
1) you have setup with a webHook (using the setWebhook method) so Telegram knows where to send your bot's requests
or
2) your bot polls Telegram's Bot-API repeatedly asking if there are any new updates (i.e. messages users sent to your bot) using the getUpdates method
Your bot receives these messages, and replies as directed by your bots "code or logic"
hope this helps.

You can run the code quite easily from your machine.
For example how I did it using NodeJS:
1)Install NodeJS on your machine (details - https://nodejs.org/en/download/package-manager/)
2)Install Node Telegram Bot API (https://github.com/yagop/node-telegram-bot-api)
3) create a file like this, filling in with necessary changes:
const TelegramBot = require('node-telegram-bot-api');
// replace the value below with the Telegram token you receive from #BotFather
const token = 'YOUR_TELEGRAM_BOT_TOKEN';
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});
// Matches "/echo [whatever]"
bot.onText(/\/echo (.+)/, (msg, match) => {
// 'msg' is the received Message from Telegram
// 'match' is the result of executing the regexp above on the text content
// of the message
const chatId = msg.chat.id;
const resp = match[1]; // the captured "whatever"
// send back the matched "whatever" to the chat
bot.sendMessage(chatId, resp);
});
// Listen for any kind of message. There are different kinds of
// messages.
bot.on('message', (msg) => {
const chatId = msg.chat.id;
// send a message to the chat acknowledging receipt of their message
bot.sendMessage(chatId, 'Received your message');
});
4) Finally launch your command console (like cmd on Windows) navigate to telegram bot directory where the script is located and type node index.js (assuming your file with the bot script like above is named index.js)
Following these steps you will have a fully functioning bot. As you make changes to index.js you can simply rerun the command "node index.js" in console.
The procedure is similar if you need to set up a bot on a server.
Hope this helps.

Related

How do I send push notifications with expo and react native?

I am writing a simple app, where I need to send push notifications. For instance, a user liked a post -> send a push notification; or a user commented under a post -> send a push notification; or a user sent you a message -> send a push notification.
I am using Notifications from expo-notifications. I have set up my Notifications.addNotificationReceivedListener and Notifications.addNotificationResponseReceivedListener. I tested them using Expo's push notification tool and it all works fine.
However, I am struggling to send notifications. As suggested per expo's docs they have a library for Node.js called expo-server-sdk-node which takes care of sending notifications. As per their doc:
The Expo push notification service accepts batches of notifications
so that you don't need to send 1000 requests to send 1000
notifications. We recommend you batch your notifications to reduce
the number of requests and to compress them (notifications with
similar content will get compressed).
And I agree with the above statement. Sending notifications on batch makes sense, however, I have a question regarding this:
How do I implement it? Do I keep counter on the user's notification, and lets say, the user has liked 10 posts -> then I send 10 notifications as a batch request? What if they liked 8 posts and then closed the app? Do I send the notifications on closing the app? It doesn't seem right to me. Also, if the user has sent a message, I believe I should straight away send the notification, rather than waiting for a batch request for the user to send 10 messages.
The implementation they offer on their docs is the following:
// Create the messages that you want to send to clients
let messages = [];
for (let pushToken of somePushTokens) {
// Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
// Check that all your push tokens appear to be valid Expo push tokens
if (!Expo.isExpoPushToken(pushToken)) {
console.error(`Push token ${pushToken} is not a valid Expo push token`);
continue;
}
// Construct a message (see https://docs.expo.io/push-notifications/sending-notifications/)
messages.push({
to: pushToken,
sound: 'default',
body: 'This is a test notification',
data: { withSome: 'data' },
})
}
Which is OK and understandable. But then I struggle with the next step:
let chunks = expo.chunkPushNotifications(messages);
let tickets = [];
(async () => {
for (let chunk of chunks) {
try {
let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
console.log(ticketChunk);
tickets.push(...ticketChunk);
} catch (error) {
console.error(error);
}
}
})();
That is, at which point do I call expo.chunkPushNotifications(messages) and then await expo.sendPushNotificationsAsync(chunk). Do I wait 10 similar notifications to be collected, do I wait some time, do I do it when the user closes the app, or something else?

How to send external messages to a specific channel with discord py?

I'm trying to forward messages to channel when I receive messages from api.
I'm using
def trigger(messagecontent):
async def messagesender():
channel = ... #get channel id
await channel.send(messagecontent)
await bot.close()
#bot.event
async def on_ready():
await messagesender()
bot.run(token=Token)`
What happens is, when I receive message from api, I call trigger(messagecontent), the bot logs in, sends message and closes, then the rest of my external script (sync version) executes.
But on the next loop, when new message from api is received, trigger(messagecontent) gives error
Runtime: Session is closed
If I don't close the bot with bot.close(), my sync script will be stuck at discord part. This is why I need to close the bot.
I don't want to use webhooks because there are many channels where messages are to be sent using the same bot.
Why are you shutting down the bot via await bot.close()?
Ofc you will get that error if you shut down the bot.

How can i read message of particular user in telegram group using telegram bot i am using node-telegram-bot

How to read particular user latest messages i have userId but i want to read all messages send by that user.
I want if there is any bot functions which can be used for this.
I also want to know can i read reactions on a particular message of that user
It's pretty easy to filter the messages by sender id. You should:
Disable the privacy mode.
A bot running in privacy mode will not receive all messages that
people send to the group.
When you have an incoming update, check for the update.message.from.id to know if he's the target user.
use copyMessage or forwardMessage to send his message to yourself.
Here's a simple example using PHP/TeleBot:
$tg = new TeleBot('your-token');
if ($tg->user->id == 'target-user-id') {
$tg->forwardMessage([
'chat_id' => 'your-user-id',
'from_chat_id' => $tg->chat->id,
'message_id' => $tg->message->message_id,
]);
}
You can also check out this repository to more know and get inspired:
https://github.com/mkleymenov/telespy-bot

Send Proactive 1:1 message in Teams using Bot Framework V4

I'm trying to send proactive 1:1 message from bot to teams using Teams SDK with the code below
MicrosoftAppCredentials.TrustServiceUrl(turnContext.Activity.ServiceUrl);
var connectorClient = new ConnectorClient(new Uri(turnContext.Activity.ServiceUrl), Configuration["MicrosoftAppId"], Configuration["MicrosoftAppPassword"]);
var userId = _operation.MemberTeamsId;
var tenantId = Configuration["TenantId"];
var parameters = new ConversationParameters
{
Members = new[] { new ChannelAccount(userId) },
ChannelData = new TeamsChannelData
{
Tenant = new TenantInfo(tenantId),
},
};
var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters);
var message = Microsoft.Bot.Schema.Activity.CreateMessageActivity();
message.Text = _operation.Message;
await connectorClient.Conversations.SendToConversationAsync(conversationResource.Id, (Microsoft.Bot.Schema.Activity)message);
I have the following issues with this,
The bot cannot send a proactive message unless the user has a prior conversation after deployment
Bot deployed
Bill to Bot - Works
Bot to Bill - Works
Bot redeployed
Bot to Bill - Not works because there are no members in the conversation now after redeploying
Bill to Bot - Works
Bot to Bill - Works now as Bill had a conversation after redeploying
Bot sends the same message multiple times to users
Bill to Bot - Works
Bot to Bill - Works Proactively - Sends 1 defined message as it should
Sim to Bot - Works
Bot to Sim - Sends 2 same messages as there are two members in the conversation now
Will to Bot - works
Bot to Will - Sends 3 same messages as there are three members in the conversation now
Note: I am storing the Teams userid in DB and use them to send direct messages to users
Any help on how to correct this would be appreciated. Thanks.
Based on the answers in the comments, I think I understand the scenario better, and it looks to me like the problem is that you're not setting a Conversation Id anyway - although you tell the Bot which user you want to interact with, it needs to know if you want to interact with them directly (i.e. 1-1), or as part of a group chat somewhere, or a Teams channel.
You need to set this by configuring the Conversation property on the Activity instance (in your case the "message" variable). See my post here for more detailed information: Programmatically sending a message to a bot in Microsoft Teams
Hope that helps - if not, let me know

Telegram Inline Bot not call webhook

I've created new bot for Telegram. I've set /setinline in BotFather for my bot. I've added a webhook that is called when I send a message to bot but this webhook is not called if I write something in the bot chat without send any message.
Any idea how to solve?
Yes, it does, probably you're inspecting the wrong param, it will call the same webhook, first remember you set the webhook by doing:
https://api.telegram.org/bot<BOT_TOKEN>/setWebhook?url=<YOUR_URL>
and like you mentioned, you need to enable /setinline through BotFather, then it will call your endpoint with a message with the following body:
{
"query":"tex",
"from": {
"username":"user",
"first_name":"firstname",
"last_name":"lastname",
"id": 8888888,
"language_code":"en-US"},
"id":"7777777",
"offset":""
}
Remember it will call your endpoint on key-up you may receive a ton of request.

Resources