elasko-aim commited on
Commit
275c612
·
verified ·
1 Parent(s): c39a54b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -56
app.py CHANGED
@@ -1,63 +1,56 @@
1
  import gradio as gr
2
- from telegram import Update
3
- from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
4
- import threading
5
-
6
- # Замените 'YOUR_TELEGRAM_BOT_TOKEN' на токен вашего бота
7
- TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
8
-
9
- # Заглушка для функции поиска партнеров (замените на реальную реализацию)
10
- def search_channels(query):
11
- # Здесь нужно добавить логику для поиска партнеров по запросу
12
- # Например, поиск по базе данных или API
13
- # Возвращает список словарей с информацией о каналах
14
- return [
15
- {"name": "Канал 1", "link": "t.me/channel1", "description": "Описание канала 1"},
16
- {"name": "Канал 2", "link": "t.me/channel2", "description": "Описание канала 2"},
17
- {"name": "Группа 3", "link": "t.me/group3", "description": "Описание группы 3"},
18
- ]
19
-
20
- async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
21
- await context.bot.send_message(chat_id=update.effective_chat.id, text="Я бот для взаимного пиара! Используйте /find <запрос> для поиска партнеров.")
22
-
23
- async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
24
- await context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)
25
-
26
- async def find_partners(update: Update, context: ContextTypes.DEFAULT_TYPE):
27
- if context.args:
28
- query = " ".join(context.args)
29
- partners = search_channels(query)
30
- if partners:
31
- message = "Найдены партнеры:\n"
32
- for partner in partners:
33
- message += f"- <a href='{partner['link']}'>{partner['name']}</a>: {partner['description']}\n"
34
- await context.bot.send_message(chat_id=update.effective_chat.id, text=message, parse_mode='HTML')
35
- else:
36
- await context.bot.send_message(chat_id=update.effective_chat.id, text="Партнеры не найдены.")
 
 
37
  else:
38
- await context.bot.send_message(chat_id=update.effective_chat.id, text="Используйте /find <запрос> для поиска партнеров.")
39
 
40
- def run_telegram_bot():
41
- app = ApplicationBuilder().token(TOKEN).build()
 
 
42
 
43
- start_handler = CommandHandler('start', start)
44
- echo_handler = CommandHandler('echo', echo)
45
- find_handler = CommandHandler('find', find_partners)
46
 
47
- app.add_handler(start_handler)
48
- app.add_handler(echo_handler)
49
- app.add_handler(find_handler)
50
 
51
- app.run_polling()
 
52
 
53
- def gradio_interface(message):
54
- # Здесь можно добавить логику для взаимодействия с Telegram ботом
55
- # Например, отправлять сообщение в г��уппу или канал
56
- return f"Отправлено сообщение: {message}"
57
-
58
- if __name__ == "__main__":
59
- telegram_thread = threading.Thread(target=run_telegram_bot)
60
- telegram_thread.start()
61
-
62
- iface = gr.Interface(fn=gradio_interface, inputs="text", outputs="text")
63
- iface.launch()
 
1
  import gradio as gr
2
+ import requests
3
+ import gspread
4
+ from oauth2client.service_account import ServiceAccountCredentials
5
+
6
+ # API Keys
7
+ DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions" # Убедитесь, что URL актуален
8
+ DEEPSEEK_API_KEY = "sk-c8fdcfbac1984ab6b2fefd0215874f11" # Замените на ваш API-ключ DeepSeek
9
+ GEO_API = "https://ipinfo.io/json"
10
+ AFFILIATE_LINK = "https://youraffiliatelink.com"
11
+
12
+ # Подключение Google Sheets
13
+ scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
14
+ creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
15
+ client = gspread.authorize(creds)
16
+ sheet = client.open("CPA_Affiliate_Analytics").sheet1
17
+
18
+ # Функция определения GEO
19
+ def get_user_geo():
20
+ response = requests.get(GEO_API)
21
+ return response.json().get("country", "Unknown")
22
+
23
+ # Генерация текста через DeepSeek API
24
+ def generate_reply(user_input):
25
+ headers = {
26
+ "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
27
+ "Content-Type": "application/json"
28
+ }
29
+ data = {
30
+ "model": "deepseek-chat", # Укажите модель DeepSeek
31
+ "messages": [
32
+ {"role": "system", "content": "Ты AI-бот, который продает казино офферы."},
33
+ {"role": "user", "content": user_input}
34
+ ]
35
+ }
36
+ response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
37
+ if response.status_code == 200:
38
+ return response.json()["choices"][0]["message"]["content"]
39
  else:
40
+ return "Ошибка при генерации ответа."
41
 
42
+ # Функция обработки запроса
43
+ def chatbot(user_input):
44
+ geo = get_user_geo()
45
+ reply_text = generate_reply(user_input)
46
 
47
+ # Сохраняем данные в Google Sheets
48
+ sheet.append_row([geo, user_input, reply_text])
 
49
 
50
+ return f"🌍 GEO: {geo}\n🤖 AI: {reply_text}\n🎰 Бонус: {AFFILIATE_LINK}"
 
 
51
 
52
+ # Интерфейс Gradio
53
+ iface = gr.Interface(fn=chatbot, inputs="text", outputs="text", title="AI-CPA Бот")
54
 
55
+ # Запуск
56
+ iface.launch()