-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
190 lines (161 loc) Β· 7.39 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
const express = require("express");
const app = express();
const TelegramBot = require('node-telegram-bot-api');
const mongoose = require('mongoose');
const axios = require('axios');
const schedule = require('node-schedule');
const User = require('./models/User')
const { OpenAI } = require('openai')
require('dotenv').config();
//Initialise MongoDB connection
mongoose.connect(process.env.MONGO_URL) //Here Use your mongoDb Url.
.then(() => console.log('DB Connected'))
.catch((err) => console.log(err));
//configure open ai api
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY //Your open ai api key.
})
// Initialize Telegram Bot
const botToken = process.env.BOT_TOKEN; //Use Bot Token which is get after creating.
const bot = new TelegramBot(botToken, { polling: true });
bot.on('message', async (msg) => {
try {
const chatId = msg.chat.id;
const text = msg.text?.toString()?.toLowerCase() ?? "Some error in parsing";
let user = await User.findOne({ chatId });
if (text === '/start' || text === '/weather' || user?.chat_type === '/weatherinfo') {
handleWeatherInfo(msg)
}
else if (text === '/newlocation' && user) {
await User.findByIdAndUpdate({ _id: user._id }, { city: '', country: '' })
handleWeatherInfo(msg)
}
else if (text === '/newlocation' && !user) {
bot.sendMessage(chatId, "π New here? Share some info to get started!");
handleWeatherInfo(msg)
}
else if (text === '/daily' && user && user.chat_type !== '/gptai') {
await User.findByIdAndUpdate({ _id: user._id }, { last_text: text })
forecastWeatherDaily(msg)
}
else if (text === '/daily' && (!user || user.chat_type === '/gptai')) {
bot.sendMessage(chatId, "π New here? Share some info to get started! Once done, click /daily in the menu!");
handleWeatherInfo(msg)
}
else {
if (!user) {
user = await User.create({
chatId: chatId,
chat_type: '/gptai',
username: msg.chat.first_name,
last_text: text
});
}
else
await User.findByIdAndUpdate({ _id: user._id }, { last_text: text, chat_type: msg.chat?.type })
const res = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: text }],
max_tokens: 50,
temperature: 0.9,
})
console.log(res.choices[0].message.content)
const finalRes = res.choices[0].message.content
bot.sendMessage(chatId, finalRes);
}
} catch (error) {
console.log(error)
bot.sendMessage(msg.chat.id, "Sorry, There is some issue. We'll get back to you soon. π");
}
});
//handle weather giving info flow
const handleWeatherInfo = async (msg) => {
try {
const chatId = msg.chat.id;
const text = msg.text?.toString()?.toLowerCase() ?? "Some error in parsing";
// const username = msg.chat.first_name //if wants by telegram username then use this...
let user = await User.findOne({ chatId });
if (!user || user.chat_type === '/gptai') {
if (!user) {
user = await User.create({
chatId: chatId,
last_text: text,
chat_type: '/weatherinfo'
});
}
else
await User.findByIdAndUpdate({ _id: user._id }, { username: '', last_text: text, chat_type: '/weatherinfo' })
bot.sendMessage(chatId, "Hi there! π What's your name?");
return;
}
else {
if (!user.username) {
await User.findByIdAndUpdate({ _id: user._id }, { username: text, last_text: text, chat_type: '/weatherinfo' })
bot.sendMessage(chatId, "Nice to meet you, " + text + "! π What city are you from?");
} else if (user.username && text === '/newlocation') {
await User.findByIdAndUpdate({ _id: user._id }, { last_text: text, chat_type: '/weatherinfo' })
bot.sendMessage(chatId, "Hi! Again," + user.username + "! π So tell me new city?");
}
else if (!user.city) {
await User.findByIdAndUpdate({ _id: user._id }, { city: text, last_text: text, chat_type: '/weatherinfo' })
bot.sendMessage(chatId, "Got it. ποΈ What country are you from?");
} else if (!user.country) {
await User.findByIdAndUpdate({ _id: user._id }, { country: text, last_text: text, chat_type: msg.chat?.type })
bot.sendMessage(chatId, "Great! You're all set. π");
const weather = await getWeather(user.city?.trim(), text?.trim(), user._id);
bot.sendMessage(user.chatId, "π€οΈ Here's Your Today Weather Update: \n" + weather);
}
else {
bot.sendMessage(chatId, "Welcome back! π ");
const weather = await getWeather(user.city?.trim(), user.country?.trim(), user._id);
bot.sendMessage(user.chatId, "π€οΈ Here's Your Today Weather Update: \n" + weather);
}
return;
}
} catch (error) {
console.log(error)
bot.sendMessage(msg.chat.id, "Daily Weather Update: π€οΈ\n" + weather);
}
}
// Schedule daily weather updates
const forecastWeatherDaily = async (msg) => {
try {
const job = schedule.scheduleJob(process.env.CRON_JOB, async () => { //cron-job "15 8 * * *"
const chatId = msg.chat.id
let user = await User.findOne({ chatId });
const weather = await getWeather(user.city.trim(), user.country.trim(), user._id);
bot.sendMessage(user.chatId, "π€οΈ Here's Your Today Weather Update: \n" + weather);
});
bot.sendMessage(msg.chat.id, "π Your daily weather updates is activated! β¨");
return
} catch (error) {
console.log(error)
bot.sendMessage(msg.chat.id, "Sorry, There is some issue. We'll get back to you soon. π");
}
}
// Function to fetch weather data
async function getWeather(city, country, id) {
try {
const apiKey = process.env.WEATHER_API_KEY; //Use Your open weather map api key.
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
const response = await axios.get(apiUrl);
const weatherData = response.data;
return `π Weather in ${city}, ${country}:\n π€οΈ ${weatherData.weather[0].description},\n π‘οΈ Temperature: ${Math.round(weatherData.main.temp)}Β°C`;
} catch (error) {
console.error("Error fetching weather:", error);
return "Sorry, couldn't fetch weather data. β";
}
}
app.get("/", (req, res) => res.send("Hello From Telegram Bot Services"));
const port = process.env.PORT || 8080
app.listen(port,()=>{
console.log(`Telegram bot services listening on port ${port}!`)
})
// bot.on('message', async (msg) => {
// const chatId = msg.chat.id
// const msgText = msg.text?.toString()?.toLowerCase()
// msg.chat.first_name
// msg.chat.type
// console.log(msg)
// bot.sendMessage(chatId, "Hi There!!");
// });