-
Notifications
You must be signed in to change notification settings - Fork 0
/
xmtpizza.js
237 lines (186 loc) · 6.24 KB
/
xmtpizza.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
const dotenv = require('dotenv');
const TelegramBot = require('node-telegram-bot-api');
const { Client } = require('@xmtp/xmtp-js');
const { ethers } = require('ethers');
dotenv.config();
const { Sequelize, DataTypes } = require('sequelize');
const connectionString = process.env.DATABASE_URL;
const sequelize = new Sequelize(connectionString, {
dialect: 'postgres',
});
const TelegramUser = sequelize.define('telegram_user', {
username: {
type: DataTypes.TEXT,
allowNull: true,
},
chat_id: {
type: DataTypes.BIGINT,
allowNull: true,
},
wallet_address: {
type: DataTypes.TEXT,
allowNull: true,
},
});
async function createTable() {
try {
await sequelize.sync();
console.log('Table "telegram_users" has been created successfully.');
} catch (error) {
console.error('Error creating table:', error);
}
}
// function sendPhoto(chatId, photoPath, caption) {
// bot.sendPhoto(chatId, photoPath, { caption: caption })
// .then(() => {
// console.log('Photo sent successfully.');
// })
// .catch((error) => {
// console.error('Error sending photo:', error.message);
// });
// }
async function getTelegramUsernames() {
try {
await sequelize.authenticate();
const users = await TelegramUser.findAll({
attributes: ['username'],
});
// Extract the usernames from the users array and store them in a new array
const usernames = users.map((user) => user.username);
console.log('Usernames:', usernames);
return usernames;
} catch (error) {
console.error('Error fetching usernames:', error);
}
}
function stringToHex(inputString) {
const utf8Bytes = ethers.utils.toUtf8Bytes(inputString);
const hexString = ethers.utils.hexlify(utf8Bytes);
return hexString;
}
function genWallet(tg) {
// Validate mnemonic and username
const mnemonic = process.env.MNEMONIC;
if (!mnemonic) {
throw new Error("Invalid mnemonic.");
}
if (!tg || typeof tg !== 'string') {
throw new Error("Invalid Telegram username.");
}
// Calculate the keccak256 hash of the combined seed
const seedBytes = ethers.utils.toUtf8Bytes(mnemonic + tg);
const keccakHash = ethers.utils.keccak256(seedBytes);
const newWallet = new ethers.Wallet(keccakHash);
return newWallet
}
async function sendXMTP(wallet, msg) {
const xmtp = await Client.create(wallet, { env: "production" });
const conversation = await xmtp.conversations.newConversation(
// "0x7A33615d12A12f58b25c653dc5E44188D44f6898" // freeslugs
'0x194c31cAe1418D5256E8c58e0d08Aee1046C6Ed0' // prod xmtp wallet
);
conversation.send(msg);
}
async function getChatIdByUsername(username) {
try {
// Connect to the database
await sequelize.authenticate();
// Find the user with the provided username
const user = await TelegramUser.findOne({
where: {
username: username,
},
});
// If the user exists, return the chat ID; otherwise, return null
return user ? user.chat_id : null;
} catch (error) {
console.error('Error fetching chat ID from the database:', error);
return null;
}
}
function initBot() {
const botToken = process.env.YOUR_TELEGRAM_API_TOKEN;
// Create a new bot instance
const bot = new TelegramBot(botToken, { polling: true });
bot.onText(/\/start/, (msg) => {
const chatId = msg.chat.id;
const username = msg.from.username;
const welcomeMessage = `Welcome to xmtpizza, @${username}! XMTP folks will deliver you goods, what do you want? toothpaste, toothbrush, tic tacs, hollywood gum, deodorant, carambar, potato chips, xmtp swag, red bull.`
bot.sendMessage(chatId, welcomeMessage);
});
// Message handler
bot.on('message', async (msg) => {
const chatId = msg.chat.id;
const messageText = msg.text ? msg.text.trim().toLowerCase() : ''; // Ensure messageText is not null
const tg = msg.from.username
const wallet = genWallet(tg);
if (messageText === '/start') {
// Handle the "/start" command separately if needed
return; // Exit the callback early
}
// Find or create the user based on the chat ID
const [user, created] = await TelegramUser.findOrCreate({
where: {
chat_id: chatId,
},
defaults: {
username: tg,
wallet_address: wallet.address
},
});
if(created) {
await spinUpXmtp(tg)
listenToXmtpMessages(tg)
}
// const xmtpMsg = `@${tg}- ${messageText}`
console.log(`chatId : ${chatId}, msg text: ${messageText}, `)
sendXMTP(wallet, messageText)
});
return bot
}
async function spinUpXmtp(tg) {
console.log(`listening to XMTP messages for ${tg}`);
// Your implementation to listen for XMTP messages goes here
const wallet = genWallet(tg);
console.log(`wallet: ${wallet.address}, ${wallet.privateKey}`)
const xmtp = await Client.create(wallet, { env: "production" });
return xmtp
}
async function listenToXmtpMessages(tg) {
const chatId = await getChatIdByUsername(tg)
const wallet = genWallet(tg);
const xmtp = await Client.create(wallet, { env: "production" });
for await (const message of await xmtp.conversations.streamAllMessages()) {
if (message.senderAddress === xmtp.address) {
// This message was sent from me
continue;
}
console.log(`New message from ${message.senderAddress}: ${message.content}`);
const botToken = process.env.YOUR_TELEGRAM_API_TOKEN;
const bot = new TelegramBot(botToken, { polling: false });
console.log(`chatId: ${chatId}; msg: ${message.content}`)
bot.sendMessage(chatId, message.content);
}
}
async function main() {
await createTable();
// Main process code
console.log(`Main process started.`);
initBot();
console.log('bot is live')
const usernames = await getTelegramUsernames()
for (var i = 0; i < usernames.length; i++) {
listenToXmtpMessages(usernames[i])
}
}
main();
async function sendAnnouncement(message) {
const botToken = process.env.YOUR_TELEGRAM_API_TOKEN;
const bot = new TelegramBot(botToken, { polling: false });
const usernames = await getTelegramUsernames();
for (const username of usernames) {
const chatId = await getChatIdByUsername(username);
bot.sendMessage(chatId, message);
}
}
// sendAnnouncement("this is @freeslugs; dinner is happening now! nom nom" )