Repository navigation
Expand file tree
/
Copy pathbot.js
More file actions
293 lines (266 loc) · 8.07 KB
/
Copy pathbot.js
File metadata and controls
293 lines (266 loc) · 8.07 KB
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
require('dotenv').config();
const { Telegraf } = require('telegraf');
const LocalSession = require('telegraf-session-local');
const axios = require('axios');
const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN);
const session = new LocalSession({
getSessionKey: (ctx) => ctx.from && ctx.from.id ? ctx.from.id.toString() : undefined
});
bot.use(session.middleware());
const models = {
text: {
'deephermeslama': {
displayName: '🦙 DeepHermes-3-Llama-3-8B-Preview',
apiModelName: 'DeepHermes-3-Llama-3-8B-Preview',
maxTokens: 256,
temperature: 0.7,
topP: 0.9
},
'deephermesmistral': {
displayName: 'DeepHermes-3-Mistral-24B-Preview',
apiModelName: 'DeepHermes-3-Mistral-24B-Preview',
maxTokens: 256,
temperature: 0.7,
topP: 0.9
},
'hermes': {
displayName: '⚡ Hermes-3-Llama-3.1-70B',
apiModelName: 'Hermes-3-Llama-3.1-70B',
maxTokens: 256,
temperature: 0.7,
topP: 0.9
},
},
image: {
'flux': {
displayName: '🎨 FLUX.1-dev',
apiModelName: 'FLUX.1-dev'
},
'sd2': {
displayName: '🖼️ SD2',
apiModelName: 'SD2'
}
},
audio: {
'melo_tts': {
displayName: '🔊 Melo TTS'
}
}
};
function showCategorySelection(ctx) {
ctx.reply('*📂 Choose a category:*', {
parse_mode: 'Markdown',
reply_markup: {
inline_keyboard: [
[{ text: '📝 Text Models', callback_data: 'category_text' }],
]
}
});
}
function showModelSelection(ctx, category) {
const modelList = models[category];
const buttons = Object.entries(modelList).map(([key, model]) => [{
text: model.displayName,
callback_data: `model_${key}`
}]);
ctx.reply(`*🔧 Choose ${category} model:*`, {
parse_mode: 'Markdown',
reply_markup: {
inline_keyboard: buttons
}
});
}
function getModelCategory(modelKey) {
for (const category in models) {
if (models[category][modelKey]) {
return category;
}
}
return null;
}
function getModelInfo(modelKey) {
for (const category in models) {
if (models[category][modelKey]) {
return models[category][modelKey];
}
}
return null;
}
const getSwitchModelKeyboard = () => ({
inline_keyboard: [
[{ text: '🔄 Switch Model', callback_data: 'switch_model' }]
]
});
async function handleModelInput(ctx, input) {
const modelKey = ctx.session.selectedModel;
const apiKey = ctx.session.apiKey;
let url, data, headers;
if (!apiKey) {
await ctx.reply('🔐 *Please send your API key first!*', { parse_mode: 'Markdown' });
return;
}
if (!modelKey) {
await ctx.reply('⚠️ *Select model first using /switch*', { parse_mode: 'Markdown' });
return;
}
const modelInfo = getModelInfo(modelKey);
if (!modelInfo) {
await ctx.reply('❌ *Model not found!*', { parse_mode: 'Markdown' });
return;
}
headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
};
const category = getModelCategory(modelKey);
if (category === 'text') await ctx.sendChatAction('typing');
else if (category === 'image') await ctx.sendChatAction('upload_photo');
else if (category === 'audio') await ctx.sendChatAction('upload_voice');
if (category === 'text') {
url = "https://inference-api.nousresearch.com/v1/chat/completions";
data = {
messages: [{ role: "user", content: input }],
model: modelInfo.apiModelName,
max_tokens: modelInfo.maxTokens,
temperature: modelInfo.temperature,
top_p: modelInfo.topP
};
} else if (category === 'image') {
url = "https://api.hyperbolic.xyz/v1/image/generation";
data = {
model_name: modelInfo.apiModelName,
prompt: input,
steps: 30,
cfg_scale: 5,
enable_refiner: false,
height: 1024,
width: 1024,
backend: "auto"
};
} else if (category === 'audio') {
url = "https://api.hyperbolic.xyz/v1/audio/generation";
data = { text: input, speed: 1 };
}
try {
const response = await axios.post(url, data, { headers });
const result = response.data;
if (category === 'text') {
const answer = result.choices[0].message.content;
await ctx.reply(`💡 ${answer}`, {
parse_mode: 'Markdown',
reply_markup: getSwitchModelKeyboard()
});
} else if (category === 'image') {
const imageData = result.images?.[0]?.image;
if (imageData) {
await ctx.replyWithPhoto(
{ source: Buffer.from(imageData, 'base64') },
{ caption: '🖼️ Generated Image', reply_markup: getSwitchModelKeyboard() }
);
} else {
await ctx.reply('❌ No image generated', { reply_markup: getSwitchModelKeyboard() });
}
} else if (category === 'audio') {
const audioData = result.audio;
if (audioData) {
await ctx.replyWithAudio(
{ source: Buffer.from(audioData, 'base64') },
{ caption: '🔊 Generated Audio', reply_markup: getSwitchModelKeyboard() }
);
} else {
await ctx.reply('❌ No audio generated', { reply_markup: getSwitchModelKeyboard() });
}
}
} catch (error) {
console.error('🚨 Error:', error);
const errorMsg = error.response?.status === 401
? '🔑 Invalid API Key'
: '⚠️ Processing Error';
await ctx.reply(`❌ ${errorMsg}`, { parse_mode: 'Markdown' });
}
}
bot.command('start', (ctx) => {
if (!ctx.session.apiKey) {
ctx.reply(
'*Welcome to Nous AI Bot*\n\n' +
'To get started, send your Nous API Key:\n' +
'1. Visit [Nous Website](https://portal.nousresearch.com/api-keys) and Log In\n' +
'2. Go to the *API Keys_* section\n' +
'3. Copy your API Key\n' +
'4. Paste it here\n\n' +
'🛡️ *Security Notice:*\n' +
'- Your API key is stored securely\n' +
'- You can remove it using /remove\n' +
'- This bot only stores your key for session access\n\n',
{
parse_mode: 'Markdown',
}
);
} else {
ctx.reply('🔁 Restarting session...');
showCategorySelection(ctx);
}
});
bot.command('switch', (ctx) => {
if (!ctx.session.apiKey) {
ctx.reply('🔒 *API key required*', { parse_mode: 'Markdown' });
} else {
showCategorySelection(ctx);
}
});
bot.command('remove', (ctx) => {
if (ctx.session.apiKey) {
delete ctx.session.apiKey;
delete ctx.session.selectedModel;
ctx.reply('🗑️ *Credentials removed*', { parse_mode: 'Markdown' });
} else {
ctx.reply('ℹ️ *No stored credentials*', { parse_mode: 'Markdown' });
}
});
bot.command('help', (ctx) => {
ctx.reply(
'📚 *Commands:*\n' +
'*/start* - Initialize bot\n' +
'*/switch* - Change model\n' +
'*/remove* - Clear data\n' +
'*/help* - Show this help',
{ parse_mode: 'Markdown' }
);
});
bot.on('text', async (ctx) => {
if (!ctx.session.apiKey) {
ctx.session.apiKey = ctx.message.text;
console.log('API Key saved:', ctx.session.apiKey);
ctx.reply('✅ *API key saved!*', { parse_mode: 'Markdown' });
showCategorySelection(ctx);
} else if (ctx.session.selectedModel) {
await handleModelInput(ctx, ctx.message.text);
} else {
ctx.reply('⚠️ *Select model first!*', { parse_mode: 'Markdown' });
}
});
bot.on('callback_query', async (ctx) => {
try {
await ctx.answerCbQuery();
const data = ctx.callbackQuery.data;
if (data === 'switch_model') {
showCategorySelection(ctx);
} else if (data.startsWith('category_')) {
const category = data.split('_')[1];
showModelSelection(ctx, category);
} else if (data.startsWith('model_')) {
const modelKey = data.replace('model_', '');
ctx.session.selectedModel = modelKey;
console.log('Model selected:', modelKey);
const modelInfo = getModelInfo(modelKey);
await ctx.reply(`🎯 Selected: ${modelInfo.displayName}`);
}
} catch (error) {
console.error('🚨 Callback Error:', error);
await ctx.reply('❌ Action failed');
}
});
bot.launch();
console.log('🤖 Bot running...');
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));