Send Messages With Telegram Using Appwrite Functions

Send Messages With Telegram Using Appwrite Functions

Create an Appwrite function to Send messages from Telegram bot using Appwrite Function.

ยท

4 min read

Hi everyone,

This is a tutorial I am going to create an Appwrite function to Send messages from Telegram bot to a Telegram chat using Appwrite functions , and execute it using Appwrite Server SDK .

Appwrite is a self-hosted solution that provides developers with a set of easy-to-use and integrate REST APIs to manage their core backend needs.

Prerequisites

Create Appwrite function

The first step is to create an appwrite function. in this tutorial, I will write the function using Nodejs .

First, create a directory of your choice, and initialize an npm project.

Next, install node-fetch dependency using npm. Here the requirement is to send HTTP request, so you can select any HTTP library.

run npm i node-fetch@2.6.1

Node-fetch doc about v3

npmi.png

Next, create an app.js file. This file will have the code to send the telegram message. we will get TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID from the environment variables . we can get data provided by the server using APPWRITE_FUNCTION_DATA environment variable.

const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;

const fetch = require("node-fetch");

const data = process.env.APPWRITE_FUNCTION_DATA;

// exit if no data is provided
if (!data) {
  console.log("no APPWRITE_FUNCTION_DATA found");
  process.exit(1);
}

// prase json data and get the message 
const payload = JSON.parse(data);
const message = payload["message"];

// send POST request to Telegram API
fetch(
  `https://api.telegram.org/${TELEGRAM_BOT_TOKEN}/sendMessage?chat_id=${TELEGRAM_CHAT_ID}&text=${message}`,

  {
    method: "POST",
  }
)
  .then((res) => res.json())
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

Telegram Bots API sendmessage

in the above function, we will assign necessary data to the variables like TELEGRAM_BOT_TOKEN , TELEGRAM_CHAT_ID, and APPWRITE_FUNCTION_DATA. Next, we will send an HTTP POST request to the Telegram API, with the TELEGRAM_BOT_TOKEN , TELEGRAM_CHAT_ID and the text we read from APPWRITE_FUNCTION_DATA .

Directory structure

dirstuct.png

Finally, create a tarfile of the project. Make sure you include node_modules directory

run

cd ..
tar -czvf appwrite-telegram-function.tar.gz appwritefunctionsdemo/

fucntions-tar.png

Now everything with local development is done in the Appwrite function. The next step is to deploy this function into Appwrite.

Setup and Deploy function to Appwrite

Login to Appwrite console, and create a project.

Screenshot 2021-10-25 at 20-30-33 Appwrite - Console.png

Next, create a function, here we are selecting Node.js 14.5 as Runtime because our function is written using Node.js.

Screenshot 2021-10-25 at 20-32-25 Appwrite - Console.png

Next, navigate to your function and click the Deploy Tag button, then click the manual tab. here we can give the command to run our function, and select the zipped code appwrite-telegram-function.tar.gz we created earlier.

Screenshot 2021-10-25 at 20-33-08 Appwrite - Function.png

Screenshot 2021-10-25 at 20-33-17 Appwrite - Function.png

After that navigate to the settings tab and setup the environment variables TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID

appwrite function setting.png

Now we have successfully set up the functions. so let's test it by executing it using Appwrite Server SDK.

for executing a function we need to create an APIKEY with execution permissions.

Let's create an APIKEY using console.Make sure you provided execution.read and execution.write permissions

crateapikey.png

Execute Appwrite function

Create a separate npm project and install Appwrite Server SDK.

get Endpoint and project ID from the project settings page.

appwrite project settings page.png

const sdk = require("node-appwrite");

// Init SDK
let client = new sdk.Client();

// create functions SDK
let functions = new sdk.Functions(client);

client
  .setEndpoint("http://54.89.140.188/v1") // Your API Endpoint
  .setProject("6176c696b2c24") // Your project ID
  .setKey( "0f74fe83bcbfa49211...4a27a26deeddd408ea879e6c"); // Your API Key

let message = encodeURI("hello from appwrite functions ๐Ÿš€");

functions
  .createExecution("6176c707eacaf", JSON.stringify({ message })) // pass Function id and function data
  .then((resolve) => {
    console.log(resolve);
  })
  .catch((reject) => {
    console.log(reject);
  });

Now let's run the script

node functions.js

functionrun.png

Now, let's view the function logs.

funcitonlogs.png

And in the telegram chat, we can see our message ๐Ÿš€ .

telegramchat.png

this can be useful to send notifications, greetings, and reminders based on your use case. Appwrite also supports triggers for Events like account creation, database update events, etc. you can refer to [Appwrite Functions doc] appwrite.io/docs/functions) for more information

Thanks for reading

share your thoughts in the comment section

cheers ๐Ÿฅ‚

ย