Skip to content

Commit

Permalink
Merge pull request #5 from davodm/telegram
Browse files Browse the repository at this point in the history
Telegram handler added for daily recap
  • Loading branch information
davodm authored Oct 24, 2023
2 parents 0442e52 + c45bab6 commit ffade0a
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 7 deletions.
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# IranCrypto Market Social Media Bot

The IranCrypto Market Social Media Bot is a powerful project that leverages Node.js and AWS Lambda to automate the generation of daily/weekly crypto market updates on social media platforms, including Twitter and Instagram. It utilizes the IranCrypto API to fetch data on the most popular cryptocurrencies and then generates insightful content, complete with engaging English-language tweets and Instagram posts.
The IranCrypto Market Social Media Bot is a powerful project that leverages Node.js and AWS Lambda to automate the generation of daily/weekly crypto market updates on social media platforms, including Twitter, Telegram and Instagram. It utilizes the IranCrypto API to fetch data on the most popular cryptocurrencies and then generates insightful content, complete with engaging English-language tweets and Instagram posts.

### Features
* **Crypto Market Data:** Fetches daily and weekly rankings of top cryptocurrencies from the IranCryptoMarket API.
* **Engaging Content Generation:** Uses ChatGPT to create compelling English-language tweets that discuss the performance, volume, and price changes of the top cryptocurrencies.
* **Instagram Image Creation:** Generates images for Instagram posts using [Node HTML to image](https://www.npmjs.com/package/node-html-to-image), based on templates created for the project.
* **Twitter Integration:** Posts generated content on Twitter using the [Twitter API V2](https://www.npmjs.com/package/twitter-api-v2), with credentials obtained using a CLI tool.
* **Instagram Posting:** Shares the generated images as both posts and stories on Instagram, utilizing the [Instagram private API](https://www.npmjs.com/package/instagram-private-api).
* **Telegram Posting:** Shares the generated images on Telegram channel, utilizing the [Node.JS Telegram Bot API](https://www.npmjs.com/package/node-telegram-bot-api).
* **Serverless Execution:** Runs daily via AWS Lambda on a cron schedule, ensuring maintenance-free execution and scalability.

## Setup & Usage
Expand Down Expand Up @@ -38,6 +39,9 @@ IG_PASSWORD=<Your Instagram password>
IG_PROXY=<Your server proxy to use Instagram>
IG_PRELOGIN=false //If you want to use prelogin simulation, set it to true
IG_STORE_SESSION=true //If you want to store session on DynamoDB, set it to true

TELEGRAM_CHANNEL_ID=<Your Telegram channel ID in number>
TELEGRAM_BOT_TOKEN=<Your Telegram bot token>
```

5. **Twitter Authentication:** Use the provided CLI tool to authenticate and configure Twitter credentials. This tool will guide you through the authentication process and generate access and refresh tokens.
Expand Down Expand Up @@ -65,6 +69,10 @@ Read more [technical details](https://github.com/PLhery/node-twitter-api-v2/blob
$ npm run instagram-auth
```

1. **Telegram Channel ID:** You can use [JSONDump Bot](https://t.me/JsonDumpBot) by forwarding a post from your channel to the bot to identify the channel id.

```sh

## Installation
1. Clone Repo
2. Run `npm install`
Expand All @@ -73,10 +81,16 @@ $ npm run instagram-auth

Whole serverless configuration will create DynamoDB table, attach the needed permissions and set the cronjob.

## Functionality
- Twitter: Share two daily tweets about total market transactions and top 3 cryptocurrencies.
- Instagram: Share a weekly post about 10 most traded cryptocurrencies.
- Telegram: Share a daily post about 10 most traded cryptocurrencies.

### Cronjob
Cronjob is set to run specificly for each controller:
- Twitter: Every day at 8:00 & 9:00 PM.
- Instagram: Every Friday at 8:00 PM.
- Telegram: Every day at 9:01 PM.

You can change cronjob settings from serverless.yml file.

Expand Down
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "irancrypto-social-bot",
"version": "0.3",
"version": "0.4",
"description": "IranCrypto.market social bot which send daily stats and trends to different platforms",
"main": "index.js",
"scripts": {
Expand All @@ -11,11 +11,12 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/davodm/irancrypto-twitter-bot.git"
"url": "git+https://github.com/davodm/irancrypto-social-bot.git"
},
"keywords": [
"twitter",
"instagram",
"telegram",
"cryptocurrency",
"irancrypto",
"serverless",
Expand All @@ -24,13 +25,14 @@
"author": "Davod Mozafari",
"license": "MIT",
"bugs": {
"url": "https://github.com/davodm/irancrypto-twitter-bot/issues"
"url": "https://github.com/davodm/irancrypto-social-bot/issues"
},
"homepage": "https://github.com/davodm/irancrypto-twitter-bot#readme",
"homepage": "https://github.com/davodm/irancrypto-social-bot#readme",
"dependencies": {
"file-type": "^18.5.0",
"handlebars": "^4.7.8",
"instagram-private-api": "^1.45.3",
"node-telegram-bot-api": "^0.63.0",
"openai": "^4.12.4",
"puppeteer-core": "21.3.7",
"re2": "^1.20.3",
Expand Down
12 changes: 10 additions & 2 deletions serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ package:
- '!./schemas/'
- '!./coverage/'
- '!./test/'
- '!./test.js'
- '!./twitterlogin.js'
- '!./test*.js'
- '!./auth/'
- '!./writable/'
- '!./README.md'
- '!node_modules/puppeteer/.local-chromium/**'

Expand Down Expand Up @@ -47,6 +48,13 @@ functions:
- arn:aws:lambda:eu-west-1:725824641220:layer:chromium:3 # Chromium v117
events:
- schedule: cron(0 20 ? * FRI *)

telegram:
handler: telegram.handler
layers:
- arn:aws:lambda:eu-west-1:725824641220:layer:chromium:3 # Chromium v117
events:
- schedule: cron(1 21 * * ? *)

resources:
Resources:
Expand Down
92 changes: 92 additions & 0 deletions telegram.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
const { getRecap } = require("./src/api");
const { abbreviateNumber, numFormat } = require("./src/number");
const { updateLastRunTime } = require("./src/dynamodb");
const { createImageFromTemplate, getRandomTheme } = require("./src/html");
const { getENV } = require("./src/env");
const TelegramBot = require("node-telegram-bot-api");
const bot = new TelegramBot(getENV("TELEGRAM_BOT_TOKEN"));

exports.handler = async function (event, context) {
// Prevent timeout from waiting event loop - Chromium
context.callbackWaitsForEmptyEventLoop = false;
try {
// Run daily recap
await dailyRecap();
// Update last run time on DynamoDB
updateLastRunTime("telegram", { type: "daily-recap" });
// Log
console.log("Daily recap published successfully on telegram!");
} catch (err) {
console.error(err);
}
};

/**
* Generate a weekly recap image and publish it on Instagram
*/
async function dailyRecap() {
try {
// Get Data from API
const data = await getRecap("daily");
// USDT Token
// const usd= data.find((item) => item.has_iran && item.symbol === 'USDT');
// Total Trade Volume
const totalVol = data
.filter((item) => item.has_iran)
.reduce((acc, item) => acc + item.irr.volume, 0);
// Filter Data
const tokens = data
.filter((item) => item.has_iran)
.map((item) => {
return {
name: item.name_en,
price: "$" + numFormat(item.usd.price_avg),
volume:
abbreviateNumber(Math.round(item.irr.volume), 1, true) + " IRR",
icon: item.icon,
};
})
.slice(0, 10);

// Create Image
const image = await createImageFromTemplate(
"table-" + getRandomTheme(),
{
tokens,
headers: ["Token", "Average Price", "Traded Volume"],
title: "Daily Recap",
subtitle: `Total traded volume today: ${abbreviateNumber(
Math.round(totalVol),
0,
true
)} IRR`,
lastUpdate: new Date().toISOString().slice(0, 10),
},
"daily.jpg"
);

console.log("generated image:", image);

if (!image) {
throw new Error("Image not generated!");
}
// Get Caption from AI
const caption = `
📈 Today's Crypto Market Recap | ${new Date().toISOString().slice(0, 10)}
📊 Total Traded Volume Today: ${numFormat(Math.round(totalVol))} IRR
Source: @irancrypto_market
Follow us on <a href="http://instagram.com/irancryptomarket">Instagram @irancryptomarket</a>
`;

// Publish the image on Telegram channel
await bot.sendPhoto(getENV("TELEGRAM_CHANNEL_ID"), image, {
caption: caption,
parse_mode: "html",
disable_web_page_preview: true,
});
} catch (err) {
throw err;
}
}

0 comments on commit ffade0a

Please sign in to comment.