-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_duplicate
466 lines (395 loc) · 19.3 KB
/
main_duplicate
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import os
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, CallbackGame
from telegram.ext import Application, ApplicationBuilder, CommandHandler, CallbackContext, CallbackQueryHandler
# ContextTypes, Dispatcher
from dotenv import load_dotenv
import requests
from urllib.parse import urlencode
import random
import string
from datetime import datetime
from flask import Flask, request
import asyncio
# Load environment variables from .env file
load_dotenv()
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
WEBHOOK_URL = os.getenv("WEBHOOK_URL") # Your webhook URL
url_plug = "https://roynek.com/alltrenders/codes/Telegram_Bot/Roynek%20Grows%20Bot"
game_url = f'{url_plug}/pre_game.html'
calendar_url = "https://docs.google.com/document/d/1lfuj6zKsNyK16RrOSvDD2AmgFedJAaR-2b5xTJwX6iw/edit?usp=sharing"
telegram_channel_url = "https://t.me/roynek_grows"
telegram_community = "https://t.me/roynek_grows_coin"
game_short_name = "roynek_grows_game"
# Enhanced logging configuration
# logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
# logger = logging.getLogger(__name__)
now = datetime.now()
formattedDate = now.strftime('%Y-%m-%d')
formattedTime = now.strftime('%I:%M:%S %p')
async def generate_strong_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
return password
import httpx
from datetime import datetime
from urllib.parse import urlencode
async def the_main(update, context, command="start"):
if update.callback_query:
query = update.callback_query
user = query.from_user
user_id = user.id
username = user.username
first_name = user.first_name
last_name = user.last_name
referrer_id = None
else:
user = update.message.from_user
user_id = user.id
username = user.username
first_name = user.first_name
last_name = user.last_name
# referrer_id = context.args[0] if context.args else None
referrer_id = None
# Extract the referral ID from the message text
if update.message and update.message.text:
command_parts = update.message.text.split()
if len(command_parts) > 1:
referrer_id = command_parts[1]
async with httpx.AsyncClient() as client:
response = await client.post(f'{url_plug}/check_user.php', data={
'username': username,
'tele_id': user_id,
'referrer_id': referrer_id,
'first_name': first_name,
'last_name': last_name
})
result = response.json()
if result["status"]:
query_params = {
'hash': result["hash"],
'tele_id': user_id,
'username': username,
'first_name': first_name,
'last_name': last_name
}
game_url_with_params = f"{game_url}?{urlencode(query_params)}"
game = CallbackGame()
keyboard = [
[InlineKeyboardButton("Play Now", callback_game=game)],
[InlineKeyboardButton("View Our Calendar", url=calendar_url)],
[InlineKeyboardButton("Join Our Telegram Channel", url=telegram_channel_url)],
[InlineKeyboardButton("Join Our Community", url=telegram_community)]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.answer(url=game_url_with_params) if (update.callback_query) else await update.message.reply_game(game_short_name=game_short_name, reply_markup=reply_markup)
else:
response = await client.post(f'{url_plug}/register_user.php', data={
'username': username,
'tele_id': user_id,
'referrer_id': referrer_id,
'first_name': first_name,
'last_name': last_name,
'email': None,
'password': await generate_strong_password(),
'third_party_id': user_id,
'signup_date': formattedDate,
'signup_time': formattedTime,
})
result = response.json()
if result["status"]:
query_params = {
'hash': result["hash"],
'tele_id': user_id,
'username': username,
'first_name': first_name,
'last_name': last_name
}
game_url_with_params = f"{game_url}?{urlencode(query_params)}"
game = CallbackGame()
keyboard = [
[InlineKeyboardButton("Play Now", callback_game=game)],
[InlineKeyboardButton("View Our Calendar", url=calendar_url)],
[InlineKeyboardButton("Join Our Telegram Channel", url=telegram_channel_url)],
[InlineKeyboardButton("Join Our Community", url=telegram_community)]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_game(game_short_name=game_short_name, reply_markup=reply_markup)
else:
await update.message.reply_text('We are having some issues. We are working on fixing it, Hope to see you around.')
# async def the_main(update: Update, context: CallbackContext, command="start"):
# if update.callback_query:
# #await handle_callback_query(update, context)
# query = update.callback_query
# user = query.from_user
# user_id = user.id
# username = user.username
# first_name = user.first_name
# last_name = user.last_name
# referrer_id = None
# # game_short_name_rec = query.game_short_name
# # print("User Details:", user_details)
# else:
# # Handle other types of updates, like messages, etc.
# # pass
# user = update.message.from_user
# user_id = user.id
# username = user.username
# first_name = user.first_name
# last_name = user.last_name
# referrer_id = context.args[0] if context.args else None
# response = requests.post(f'{url_plug}/check_user.php', data={
# 'username': username,
# 'tele_id': user_id,
# 'referrer_id': referrer_id,
# 'first_name': first_name,
# 'last_name': last_name
# })
# result = response.json()
# if result["status"]:
# query_params = {
# 'hash': result["hash"],
# 'tele_id': user_id,
# 'username': username,
# 'first_name': first_name,
# 'last_name': last_name
# }
# game_url_with_params = f"{game_url}?{urlencode(query_params)}"
# game = CallbackGame()
# # buttons = [[InlineKeyboardButton(text="Show Menu",callback_game=game)]]
# keyboard = [
# # [InlineKeyboardButton("Play Now", url=game_url_with_params)],
# [InlineKeyboardButton("Play Now",callback_game=game)],
# [InlineKeyboardButton("View Our Calendar", url=calendar_url)],
# [InlineKeyboardButton("Join Our Telegram Channel", url=telegram_channel_url)],
# [InlineKeyboardButton("Join Our Community", url=telegram_community)]
# ]
# reply_markup = InlineKeyboardMarkup(keyboard)
# # welcome_message = (
# # f"🎉 Welcome {username}! 🎉 You are now a Roynekian with Grows Powers \n\n"
# # "We're thrilled to have you here. Unlike other Telegram token games, "
# # "we are committed and sure of our launch date.\n\n"
# # "Click the button below to start playing the game: You can only use this button once. \n\n"
# # "To enjoy another session, give the /play command again \n\n"
# # "Stay updated with our proposed calendar below.\n\n"
# # "Join our Telegram channel for the latest updates and community discussions."
# # ) if (command == "start") else (
# # "Click the button below to start playing the game: It is a one time button, you can not use it again. \n\n "
# # "We have improved the security of telegram games. To enjoy another session, give the /play command again \n\n"
# # "Stay updated with our proposed calendar below.\n\n"
# # "Join our Telegram channel for the latest updates and community discussions."
# # )
# # await update.message.reply_text(welcome_message, reply_markup=reply_markup)
# # await update.message.reply_game(game_short_name=game_short_name,reply_markup=reply_markup)
# await query.answer(url=game_url_with_params) if (update.callback_query) else await update.message.reply_game(game_short_name=game_short_name,reply_markup=reply_markup)
# # await context.bot.send_game(chat_id=update.effective_chat.id,game_short_name=game_short_name,reply_markup=reply_markup)
# else:
# response = requests.post(f'{url_plug}/register_user.php', data={
# 'username': username,
# 'tele_id': user_id,
# 'referrer_id': referrer_id,
# 'first_name': first_name,
# 'last_name': last_name,
# 'email': None,
# 'password': await generate_strong_password(),
# 'third_party_id': user_id,
# 'signup_date': formattedDate,
# 'signup_time': formattedTime,
# })
# result = response.json()
# if result["status"]:
# query_params = {
# 'hash': result["hash"],
# 'tele_id': user_id,
# 'username': username,
# 'first_name': first_name,
# 'last_name': last_name
# }
# game_url_with_params = f"{game_url}?{urlencode(query_params)}"
# game = CallbackGame()
# # buttons = [[InlineKeyboardButton(text="Show Menu",callback_game=game)]]
# keyboard = [
# # [InlineKeyboardButton("Play Now", url=game_url_with_params)],
# [InlineKeyboardButton(text="Play Now",callback_game=game)],
# [InlineKeyboardButton("View Our Calendar", url=calendar_url)],
# [InlineKeyboardButton("Join Our Telegram Channel", url=telegram_channel_url)],
# [InlineKeyboardButton("Join Our Community", url=telegram_community)]
# ]
# reply_markup = InlineKeyboardMarkup(keyboard)
# # welcome_message = (
# # f"🎉 Welcome {username}! 🎉 You are now a Roynekian with Grows Powers \n\n"
# # "We're thrilled to have you here. Unlike other Telegram token games, "
# # "we are committed and sure of our launch date.\n\n"
# # "Click the button below to start playing the game:\n\n"
# # "Stay updated with our proposed calendar below.\n\n"
# # "Join our Telegram channel for the latest updates and community discussions."
# # ) if (command == "start") else (
# # "Click the button below to start playing the game:\n\n"
# # "Stay updated with our proposed calendar below.\n\n"
# # "Join our Telegram channel for the latest updates and community discussions."
# # )
# # Send the welcome message with inline buttons
# # await update.message.reply_text(welcome_message, reply_markup=reply_markup)
# # Send the game message
# # await context.bot.send_game(chat_id=update.effective_chat.id, game_short_name=game_short_name)
# # await context.bot.send_game(chat_id=update.effective_chat.id, game_short_name=game_short_name)
# # update.message.reply_text(welcome_message)
# await update.message.reply_game(game_short_name=game_short_name, reply_markup=reply_markup)
# # await context.bot.send_game(chat_id=update.effective_chat.id, game_short_name=game_short_name, reply_markup=reply_markup)
# else:
# await update.message.reply_text('We are having some issues. We are working on fixing it, Hope to see you around.')
async def start(update: Update, context: CallbackContext):
user = update.message.from_user
username = user.username
welcome_message = (f"🎉 Welcome {username}! 🎉 You are now a Roynekian with Grows Powers \n\n"
"We're thrilled to have you here. Unlike other Telegram token games, "
"we are committed and sure of our launch date.\n\n"
"Click the button below to start playing the game: You can only use this button once. \n\n"
"To enjoy another session, give the /play command again \n\n"
"Stay updated with our proposed calendar below.\n\n"
"Join our Telegram channel for the latest updates and community discussions.")
await update.message.reply_text(welcome_message)
#await the_main(update=update, context=context, command="start")
async def play(update: Update, context: CallbackContext):
await the_main(update=update, context=context, command="play")
async def referral(update: Update, context: CallbackContext):
user = update.message.from_user
user_id = user.id
referral_link = f"https://t.me/RoynekGrowsBot?start={user_id}"
await update.message.reply_text(f'Your referral link is: {referral_link}')
async def present_game(update: Update, context: CallbackContext):
#add game_short_name value (despite the doc saying theres no need to add it)
# game.game_short_name=game_short_name
#Create the actual button
# buttons = [[InlineKeyboardButton(text="Show Menu", url=game_url ,callback_game=game)]]
game = CallbackGame()
buttons = [[InlineKeyboardButton(text="Play",callback_game=game)]]
#Send game with custom inline button
keyboard_markup = InlineKeyboardMarkup(buttons)
await context.bot.send_game(chat_id=update.effective_chat.id,game_short_name=game_short_name,reply_markup=keyboard_markup)
async def handle_callback_query(update: Update, context: CallbackContext):
await the_main(update=update, context=context, command="play")
# query = update.callback_query
# user = query.from_user
# user_details = {
# "id": user.id,
# "first_name": user.first_name,
# "last_name": user.last_name,
# "username": user.username,
# "language_code": user.language_code
# }
# game_short_name_rec = query.game_short_name
# print("User Details:", user_details)
# Answer the callback query with the game URL
# await query.answer(url=game_url)
# query = update.callback_query
# print(query)
# # Answer the callback query with the game URL
# await query.answer(url=game_url)
async def handler(update, context):
# Telegram understands UTF-8, so encode text for unicode compatibility
text = str(update.message.text.encode('utf-8').decode() )
print("got text message :", text)
if ("//start" in text and len(text) <= 10):
print("went here 1")
#await start(update, context)
elif("//play" in text and len(text) <= 10):
await play(update, context)
print("went here 2")
elif("//referral" in text and len(text) <= 10):
await referral(update, context)
print("went here 3")
else:
print("went here 4")
# text = update.message.text.encode('utf-8').decode()
# print("got text message :", text)
# chat_id = update.message.chat.id
# msg_id = update.message.message_id
# response = "hello made..."
# # await application.bot.send_message(chat_id=chat_id, text=response, reply_to_message_id=msg_id)
# await referral(update, context)
# from quart import Quart, request
from fastapi import FastAPI, Request, Response
from contextlib import asynccontextmanager
from http import HTTPStatus
from telegram import Update
from telegram.ext import Application, CommandHandler
from telegram.ext._contexttypes import ContextTypes
# # Initialize the bot application
# application = Application.builder().token(BOT_TOKEN).build()
# Initialize python telegram bot
application = (
Application.builder()
.updater(None)
.token(BOT_TOKEN) # replace <your-bot-token>
.read_timeout(7)
.get_updates_read_timeout(42)
.build()
)
@asynccontextmanager
async def lifespan(_: FastAPI):
await application.bot.setWebhook(f"{WEBHOOK_URL}/webhook") # replace <your-webhook-url>
async with application:
await application.start()
yield
await application.stop()
# app = Quart(__name__)
# app = Flask(__name__)
# Initialize FastAPI app (similar to Flask)
app = FastAPI(lifespan=lifespan)
@app.post("/webhook")
async def process_update(request: Request):
req = await request.json()
print(req)
update = Update.de_json(req, application.bot)
await application.process_update(update)
# await handler(update, application)
return Response(status_code=HTTPStatus.OK)
# Example handler
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
print("entered the start side of the stuff")
await update.message.reply_text("starting...")
# Add the command handler to the application
application.add_handler(CommandHandler("start", start))
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s', level=logging.INFO)
logger = logging.getLogger(__name__)
start_handler = CommandHandler('start', start)
play_handler = CommandHandler('play', play)
referral_handler = CommandHandler('referral', referral)
application.add_handler(start_handler)
application.add_handler(play_handler)
application.add_handler(referral_handler)
# @app.route('/webhook', methods=['POST'])
# def webhook():
# try:
# data = request.get_json(force=True)
# # print(data["message"]["text"])
# message = data.get('message', '') # Ensure you correctly extract the 'text' field
# print("Received text:", message) # Check the extracted text
# update = Update.de_json(data, application.bot)
# # print(update)
# # # get the chat_id to be able to respond to the same user
# chat_id = update.message.chat.id
# # # get the message id to be able to reply to this specific message
# msg_id = update.message.message_id
# # # Telegram understands UTF-8, so encode text for unicode compatibility
# # text = update.message.text
# # print(f"got text message : {text}: {update.message.chat.first_name}: {update.message.chat.username} ")
# # Handle the update through the application
# # asyncio.run(application.process_update(update_) )
# # await application.process_update(update)
# # here we call our super AI
# # response = get_response(text)
# response = "hello made..."
# # now just send the message back
# # notice how we specify the chat and the msg we reply to
# # asyncio.run(application.bot.send_message(chat_id=chat_id, text=response, reply_to_message_id=msg_id) )
# # application.bot.sendMessage(chat_id=chat_id, text=response, reply_to_message_id=msg_id)
# asyncio.run( handler(update, application) )
# # await handler(update, application)
# return 'ok'
# except Exception as e:
# logger.error(f"Error processing webhook: {e}")
# if __name__ == '__main__':
# app.run(debug=True, port=8000)
# app.run(port=8000)