-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
169 lines (141 loc) · 5.6 KB
/
main.py
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
# important variables
TOKEN = 'Telegram Token'
SITE = 'Web Server URL'
# initialising bot
import telebot
bot = telebot.TeleBot(TOKEN, threaded = False)
bot.delete_webhook()
# initialising flask app
import os
from flask import Flask,request
app = Flask(__name__)
# setting up logger
import logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
#importing classes
from objects import SinglePlayer, MultiPlayer
# custom filters for bot
def is_admin(message : telebot.types.Message):
return bot.get_chat_member(message.chat.id,message.from_user.id).status in ['administrator','creator']
def is_private(message : telebot.types.Message):
if message.chat.type == 'private':
# print(message.chat.type)
return True
return False
def getName(message : telebot.types.Message):
if message.from_user.username :
name = message.from_user.username
else:
name = str(message.from_user.first_name)
if message.from_user.last_name:
name += str(message.from_user.last_name)
return name
"""All Private command handler handlers"""
@bot.message_handler(commands=['start'])
def pStart(message : telebot.types.Message):
if is_private(message):
name=getName(message)
SinglePlayer.new(message.chat.id, name)
bot.send_message(message.chat.id, "Click /newgame to start a new Tic-Tac-Toe game.")
@bot.message_handler(commands=["newgame"])
def pNewGame(message : telebot.types.Message):
if is_private(message):
SinglePlayer.newGame(message.chat.id, getName(message))
a = SinglePlayer.getBoard(message.chat.id)
markup = a.inputMarkup()
bot.send_message(message.chat.id, "Your Turn First", reply_markup=markup)
@bot.message_handler(commands=["help"], )
def pHelp(message : telebot.types.Message):
if is_private(message):
bot.send_message(message.chat.id, """
❌⭕❌⭕❌⭕❌⭕
/start - restart the bot
/newgame - start a new game
/stats - view stats
/help - show help
❌⭕❌⭕❌⭕❌⭕
""")
@bot.message_handler(commands=["stats"])
def pStats(message : telebot.types.Message):
if is_private(message):
sta = SinglePlayer.stats(message.chat.id)
try:
wd=((sta['win'])/(sta['games']))
except ZeroDivisionError:
wd=0
bot.send_message(message.chat.id, f"""
❌⭕❌⭕❌⭕❌⭕
```
Games Played - {sta['games']}
Wins - {sta['win']}
Ties - {sta['tie']}
Loses - {sta['lose']}
Win Ratio - {"{:.2f}".format(wd)} { '🔥' if (wd>0.19) else ''}{ '🔥' if (wd>0.29) else ''}{ '🔥' if (wd>0.39) else ''}
```
❌⭕❌⭕❌⭕❌⭕
""")
def pGameLoop(call):
if call.data == "pass":
return
n = int(call.data)
brd = SinglePlayer.getBoard(call.message.chat.id)
brd.all_items = [brd.a1, brd.a2, brd.a3, brd.b1, brd.b2, brd.b3, brd.c1, brd.c2, brd.c3]
if brd.all_items[n-1]==0:
brd.entry(n, 'X')
brd.modify(call.message.chat.id)
check = brd.validate()
if check == True:
bot.delete_message(call.message.chat.id, call.message.id)
bot.send_message(call.message.chat.id, "You won the game! 🥳\n\n Press /newgame to start a New Game.")
SinglePlayer.win(call.message.chat.id)
elif check == 'Draw':
bot.delete_message(call.message.chat.id, call.message.id)
bot.send_message(call.message.chat.id, "It's a Tie! 🙄\n\n Press /newgame to start a New Game.")
SinglePlayer.tie(call.message.chat.id)
else:
bot.edit_message_text("Bot's Turn", call.message.chat.id, call.message.id, reply_markup=brd.inputMarkup(no_input=True))
brd.ai_move()
brd.modify(call.message.chat.id)
bot_check = brd.validate()
if bot_check == True:
bot.delete_message(call.message.chat.id, call.message.id)
bot.send_message(call.message.chat.id, "You won the game! 🥳\n\n Press /newgame to start a New Game.")
SinglePlayer.win(call.message.chat.id)
elif bot_check == "Lose":
bot.delete_message(call.message.chat.id, call.message.id)
bot.send_message(call.message.chat.id, "Oops, You lost! 😟\n\n Press /newgame to start a New Game.")
SinglePlayer.lose(call.message.chat.id)
elif bot_check == False:
bot.edit_message_text("Your Turn", call.message.chat.id, call.message.id, reply_markup=brd.inputMarkup())
else:
bot.delete_message(call.message.chat.id, call.message.id)
bot.send_message(call.message.chat.id, "It's a Tie! 🙄\n\n Press /newgame to start a New Game.")
SinglePlayer.tie(call.message.chat.id)
@bot.callback_query_handler(func=lambda call:True)
def call_back_director(call):
if is_private(call.message):
pGameLoop(call)
else:
pass
"""!!! for development only !!!"""
# bot.infinity_polling()
@app.route('/' + TOKEN, methods=['POST'])
def getMessage():
try:
bot.remove_webhook()
bot.set_webhook(url=(SITE + TOKEN))
except Exception:
pass
json_string = request.get_data().decode('utf-8')
update = telebot.types.Update.de_json(json_string)
bot.process_new_updates([update])
return "!", 200
@app.route("/")
def webhook():
bot.remove_webhook()
bot.set_webhook(url=(SITE + TOKEN))
return "HIIII", 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))