-
Notifications
You must be signed in to change notification settings - Fork 0
/
edenBot.py
607 lines (499 loc) · 31.8 KB
/
edenBot.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
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
import asyncio
import time
import datetime as datetime
from chain import EdenData
from chain.dfuse import *
from chain.electionStateObjects import EdenBotMode, CurrentElectionStateHandlerRegistratrionV1, \
CurrentElectionStateHandlerSeedingV1, CurrentElectionStateHandlerInitVotersV1, CurrentElectionStateHandlerActive, \
CurrentElectionStateHandlerFinal, CurrentElectionStateHandler
from chain.memberState import MemberState
from chain.stateElectionState import ElectCurrTable
from community import CommunityList, CommunityListState, CommunityGroup
from constants import dfuse_api_key, telegram_api_id, telegram_api_hash, telegram_bot_token, CurrentElectionState, \
eden_account, telegram_user_bot_name, telegram_bot_name, community_group_id, community_group_testing
from database import Database, Election, ElectionStatus, Reminder
from database.comunityParticipant import CommunityParticipant
from transmissionCustom import CustomMember, AdminRights, MemberStatus, Promotion
from sbt import SBT
from database.election import ElectionRound
from log import Log
from datetime import datetime, timedelta
from debugMode.modeDemo import ModeDemo, Mode
from groupManagement import GroupManagement
from transmission import Communication, SessionType
from multiprocessing import Process
class EdenBotException(Exception):
pass
LOG = Log(className="EdenBot")
REPEAT_TIME = {
EdenBotMode.ELECTION: 45, # every 45 seconds
EdenBotMode.NOT_ELECTION: 60 * 10 # every half hour 60 seconds x 10 minutes
}
class EdenBot:
botMode: EdenBotMode
def __init__(self, edenData: EdenData, telegramApiID: int, telegramApiHash: str, botToken: str, database: Database,
mode: Mode, modeDemo: ModeDemo = None):
try:
LOG.info("Initialization of EdenBot")
assert isinstance(edenData, EdenData), "edenData is not an instance of EdenData"
assert isinstance(telegramApiID, int), "telegramApiID is not an integer"
assert isinstance(telegramApiHash, str), "telegramApiHash is not a string"
assert isinstance(botToken, str), "botToken is not a string"
assert isinstance(database, Database), "database is not an instance of Database"
assert isinstance(mode, Mode), "mode is not an instance of Mode"
assert isinstance(modeDemo, (ModeDemo, type(None))), "modeDemo is not an instance of ModeDemo or None"
self.database = database
# fill database with election status data if table is empty
self.database.fillElectionStatuses()
self.mode = mode
self.modeDemo = modeDemo
# if demo mode is set, then 'modeDemo' must be set
if mode == Mode.DEMO:
assert modeDemo is not None
self.edenData = edenData
if mode == Mode.DEMO and False:
responseStart: Response = self.edenData.getBlockNumOfTimestamp(modeDemo.getStart())
responseEnd: Response = self.edenData.getBlockNumOfTimestamp(modeDemo.getEnd())
if isinstance(responseStart, ResponseError) or isinstance(responseEnd, ResponseError):
LOG.exception("Error when called getBlockNumOfTimestamp; Description: " + responseStart.error)
raise EdenBotException("Error when called getBlockNumOfTimestamp. Raise exception")
self.modeDemo.setStartBlockHeight(responseStart.data) # set start block height
self.modeDemo.setEndBlockHeight(responseEnd.data) # set end block height
# create communication object
LOG.debug("Initialization of telegram bot...")
self.communication = Communication(database=database, edenData=edenData)
# to run callback part of pyrogram library on separated thread - not as separated executable file
self.communication.startCommAsyncSession(apiId=telegramApiID, apiHash=telegramApiHash, botToken=botToken)
self.communication.startComm(apiId=telegramApiID,
apiHash=telegramApiHash,
botToken=botToken)
LOG.debug("Creating first communication session user bot to bot if not yet created")
self.sayHelloFromUserBotToBot(userBotUsername=telegram_user_bot_name,
botUsername=telegram_bot_name)
LOG.debug("Creating community group management object ...")
#while True:
# time.sleep(2)
# make sure that testing is set correct!
self.communityGroupManagement: CommunityGroup = CommunityGroup(edenData=self.edenData,
communication=self.communication,
database=database,
mode=self.modeDemo,
testing=community_group_testing)
LOG.debug(" ...and group management object ...")
self.groupManagement = GroupManagement(edenData=edenData,
database=self.database,
communication=self.communication,
mode=mode)
LOG.debug("... is finished")
# set current election state
self.currentElectionStateHandler: CurrentElectionStateHandler = None
self.setCurrentElectionStateAndCallCustomActions(contract=eden_account, database=self.database)
except Exception as e:
LOG.exception("Exception in EdenBot.init. Description: " + str(e))
def sayHelloFromUserBotToBot(self, userBotUsername: str, botUsername: str):
try:
self.communication.updateKnownUserData(botName=botUsername)
if self.communication.knownUserData.getKnownUsersOptimizedOnlyBoolean(botName=botUsername,
telegramID=str(userBotUsername)) \
is False:
response: bool= self.communication.sendMessage(sessionType=SessionType.USER,
chatId=str(botUsername),
text="/start")
if response:
LOG.success("EdenBot.sayHelloFromUserBotToBot; Message sent to bot")
else:
LOG.error("EdenBot.sayHelloFromUserBotToBot; Message not sent to bot")
except Exception as e:
LOG.exception("Exception in EdenBot.sayHelloFromUserBotToBot. Description: " + str(e))
def manageElectionInDB(self, electionsStateStr: str, data: dict, contract: str, database: Database) -> Election:
assert isinstance(electionsStateStr, str), "electionsStateStr is not a string"
assert isinstance(data, dict), "data is not a dict"
assert isinstance(contract, str), "contract is not a string"
assert isinstance(database, Database), "database is not an instance of Database"
try:
electionState = electionsStateStr
election: Election = None
electionStatusIDfromDB = None
if electionState == "current_election_state_registration_v1":
self.currentElectionStateHandler = CurrentElectionStateHandlerRegistratrionV1(data)
# get election state from the database
electionStatusIDfromDB: ElectionStatus = \
database.getElectionStatus(self.currentElectionStateHandler.currentElectionState)
if electionStatusIDfromDB == None:
LOG.exception("EdenBot.manageElectionInDB; 'Election status' not found in database")
raise Exception("EdenBot.manageElectionInDB; 'Election status' not found in database")
# set election data to save in the database
election: Election = Election(date=datetime.fromisoformat(
self.currentElectionStateHandler.getStartTime()),
status=electionStatusIDfromDB,
contract=contract)
elif electionState == "current_election_state_seeding_v1":
self.currentElectionStateHandler = CurrentElectionStateHandlerSeedingV1(data)
# get election state from the database
electionStatusIDfromDB: ElectionStatus = \
database.getElectionStatus(self.currentElectionStateHandler.currentElectionState)
if electionStatusIDfromDB == None:
LOG.exception("EdenBot.manageElectionInDB; 'Election status' not found in database")
raise Exception("EdenBot.manageElectionInDB; 'Election status' not found in database")
# set election data to save in the database
election: Election = Election(date=datetime.fromisoformat(
self.currentElectionStateHandler.getSeedEndTime()),
status=electionStatusIDfromDB,
contract=contract)
elif electionState == "current_election_state_init_voters_v1":
self.currentElectionStateHandler = CurrentElectionStateHandlerInitVotersV1(data)
elif electionState == "current_election_state_active":
self.currentElectionStateHandler = CurrentElectionStateHandlerActive(data)
elif electionState == "current_election_state_final":
self.currentElectionStateHandler = CurrentElectionStateHandlerFinal(data)
else:
raise EdenBotException("Unknown current election state: " + str(electionState))
if election is not None:
LOG.debug("Pre-election state: " + str(election))
LOG.info("Save election to database ( +creating reminders) : " + str(election))
if electionStatusIDfromDB is None:
LOG.exception("EdenBot.manageElectionInDB; 'Election status' is None")
raise Exception("EdenBot.manageElectionInDB; 'Election status' is None")
# setting new election + creating notification records
election = database.setElection(election=election, electionStatus=electionStatusIDfromDB)
database.createRemindersIfNotExists(election=election)
# create (if not exists) dummy elections for storing free room data
database.createElectionForFreeRoomsIfNotExists(contract=contract, election=election)
else:
LOG.info("Election is in progress. Get it from database...")
election = database.getLastElection(contract=contract)
if election is None:
raise EdenBotException("EdenBot.manageElectionInDB: Election is None.")
#########################
# write current election state to database
previousElectionState: CurrentElectionState = \
database.updateElectionColumnElectionStateIfChanged(election=election,
currentElectionState=
self.currentElectionStateHandler.
currentElectionState)
if previousElectionState is not None:
LOG.debug("Previous election state: " + str(previousElectionState.value) + " changed to: "
+ str(self.currentElectionStateHandler.currentElectionState.value))
else:
LOG.debug("Election state is not changed")
# election state is active and changed
if self.currentElectionStateHandler.getIsInLive():
if isinstance(self.currentElectionStateHandler, CurrentElectionStateHandlerActive):
currentRound: int = self.currentElectionStateHandler.getRound()
else:
#election state final
currentRound: int = ElectionRound.FINAL.value
previousRound: int = database.updateElectionRoundLive(election=election, currentRound=currentRound)
if previousRound is not None and previousRound != currentRound:
#if round changed - set flag ; there will be functions that are called only when round is changed
LOG.debug("Current round is changed from " + str(previousRound) + " to: " + str(currentRound))
self.currentElectionStateHandler.setIsRoundChanged(isChanged=True,
round=previousRound)
# update election round in live object
election.roundLive = currentRound
else:
LOG.debug("Current round is not changed")
self.currentElectionStateHandler.setIsRoundChanged(isChanged=False)
##########################
# return current election state
return election
except Exception as e:
LOG.exception("Exception in manageElectionInDB. Description: " + str(e))
return None
def getElectionState(self) -> ElectCurrTable:
try:
edenData: Response = self.edenData.getElectionState(height=self.modeDemo.currentBlockHeight if \
self.modeDemo is not None else None)
if isinstance(edenData, ResponseError):
raise EdenBotException("Error when called eden.getElectionState; Description: " + edenData.error)
if isinstance(edenData.data, ResponseError):
raise EdenBotException("Error when called eden.getElectionState; Description: " + edenData.data.error)
receivedData = edenData.data
electCurrTable: ElectCurrTable = ElectCurrTable(receivedData)
if electCurrTable.type != "election_state_v0":
raise EdenBotException("Unknown election state type: " + str(electCurrTable.type))
return electCurrTable
except Exception as e:
LOG.exception("Exception in getElectionState. Description: " + str(e))
return None
"""def getMemberState(self) -> MemberState:
# get member table from chain
try:
edenData: Response = self.edenData.getMemberState(height=self.modeDemo.currentBlockHeight if \
self.modeDemo is not None else None)
if isinstance(edenData, ResponseError):
raise EdenBotException("Error when called eden.getMemberState; Description: " + edenData.error)
if isinstance(edenData.data, ResponseError):
raise EdenBotException("Error when called eden.getMemberState; Description: " + edenData.data.error)
receivedData = edenData.data
memberState: MemberState = MemberState(receivedData)
if memberState.type != "member_v1":
raise EdenBotException("Unknown member state type: " + str(electCurrTable.type))
return memberState
except Exception as e:
LOG.exception("Exception in getElectionState. Description: " + str(e))
return None"""
def groupMaintenance(self, contactAccount: str, communityGroupID: int, electionCurrState: ElectCurrTable):
assert isinstance(contactAccount, str), "contactAccount is not a string"
assert isinstance(communityGroupID, int), "communityGroupID is not an integer"
assert isinstance(electionCurrState, ElectCurrTable), "electionCurrState is not an instance of ElectCurrTable"
try:
LOG.debug("Group maintenance for group: " + str(communityGroupID))
#executionTime = datetime.now() - timedelta(hours=1)
#we are going back for 3 hours because of different time zones and also graphQL has some problems
# when we are trying to search until current time
executionTime = self.modeDemo.getCurrentBlockTimestamp() if self.modeDemo.isLiveMode() is True \
else datetime.now() - timedelta(hours=3)
TOKEN_NAME = "groupMaintenance"
#if testing is true, run it no matter what
needToRun: bool = False if self.communityGroupManagement.testing == False else True
if self.database.checkIfTokenExists(name=TOKEN_NAME) == False:
#if token does not exist, run it first time sunday at 12 PM
if executionTime.weekday() == 6 and executionTime.hour == 12:
expiration = (executionTime + timedelta(days=7)).replace(minute=0)
self.database.writeToken(name=TOKEN_NAME, value=str(1), expireBy=expiration)
LOG.debug("Token is written as current time is Sunday 12 AM")
needToRun = True
else:
if self.database.checkIfTokenExpired(name=TOKEN_NAME, executionTime=executionTime):
expiration = (executionTime + timedelta(days=7)).replace(minute=0)
self.database.writeToken(name=TOKEN_NAME, value=str(1), expireBy=expiration)
needToRun = True
if needToRun:
LOG.debug("Run group maintenance...")
self.communityGroupManagement.do(contactAccount=contactAccount,
executionTime=executionTime,
communityGroupID=communityGroupID,
electionCurrState=electionCurrState)
except Exception as e:
LOG.exception("Exception in groupMaintenance. Description: " + str(e))
return None
def setCurrentElectionStateAndCallCustomActions(self, contract: str, database: Database):
try:
assert isinstance(contract, str), "contract is not a string"
assert isinstance(database, Database), "database is not an instance of Database"
LOG.debug("Check current election state from blockchain on height: " + str(
self.modeDemo.getCurrentBlock()) if self.modeDemo is not None else "<current/live>")
edenData: Response = self.edenData.getCurrentElectionState(height=self.modeDemo.currentBlockHeight
if self.modeDemo is not None else None)
if isinstance(edenData, ResponseError):
raise EdenBotException(
"Error when called eden.getCurrentElectionState; Description: " + edenData.error)
if isinstance(edenData.data, ResponseError):
raise EdenBotException(
"Error when called eden.getCurrentElectionState; Description: " + edenData.data.error)
receivedData = edenData.data
# initialize state, create election(+dummy elections) and create notification rows in database
election: Election = self.manageElectionInDB(electionsStateStr=receivedData[0],
data=receivedData[1],
contract=contract,
database=database)
if election is None:
LOG.exception("EdenBot.setCurrentElectionStateAndCallCustomActions; 'Election' is None")
raise Exception("EdenBot.setCurrentElectionStateAndCallCustomActions; 'Election' is None")
# get current election state to manage business logic
currentElectionState = self.currentElectionStateHandler.currentElectionState
if currentElectionState == CurrentElectionState.CURRENT_ELECTION_STATE_REGISTRATION_V1:
#should be called only one time at the beginning of running the bot
communityGroupIdInt: int = None
try:
if isinstance(community_group_id, str):
communityGroupIdInt = int(community_group_id)
elif isinstance(community_group_id, int):
communityGroupIdInt = community_group_id
else:
raise Exception("ChatId is not str or int")
except Exception as e:
LOG.exception("Not int value stored in string: " + str(e))
return None
electionCurrState: ElectCurrTable = self.getElectionState()
#call only when election is in registration state, because of the complexity of the function
self.groupMaintenance(contactAccount=contract,
communityGroupID=communityGroupIdInt,
electionCurrState=electionCurrState)
self.currentElectionStateHandler.customActions(election=election,
electCurr=electionCurrState,
database=database,
groupManagement=self.groupManagement,
edenData=self.edenData,
communication=self.communication,
contract=contract,
modeDemo=self.modeDemo)
elif currentElectionState == CurrentElectionState.CURRENT_ELECTION_STATE_SEEDING_V1:
self.currentElectionStateHandler.customActions(election=election,
database=database,
groupManagement=self.groupManagement,
contract=contract,
edenData=self.edenData,
communication=self.communication,
modeDemo=self.modeDemo)
elif currentElectionState == CurrentElectionState.CURRENT_ELECTION_STATE_INIT_VOTERS_V1:
self.currentElectionStateHandler.customActions()
elif currentElectionState == CurrentElectionState.CURRENT_ELECTION_STATE_ACTIVE:
self.currentElectionStateHandler.customActions(election=election,
groupManagement=self.groupManagement,
database=database,
edenData=self.edenData,
contract=contract,
communication=self.communication,
modeDemo=self.modeDemo)
elif currentElectionState == CurrentElectionState.CURRENT_ELECTION_STATE_FINAL:
self.currentElectionStateHandler.customActions(election=election,
groupManagement=self.groupManagement,
contract=contract,
modeDemo=self.modeDemo)
else:
raise EdenBotException("Unknown current election state: " + str(receivedData[0]))
LOG.debug("Current election state: " + str(receivedData[0]) + " with data: ".join(
['{0}= {1}'.format(k, v) for k, v in receivedData[1].items()]))
if election is None:
raise EdenBotException("Election is still None - not set in database")
except Exception as e:
LOG.exception("Exception in setCurrentElectionStateAndCallCustomActions. Description: " + str(e))
def start(self):
LOG.info("Starting EdenBot")
try:
i = 0
while True:
try:
# sleep time depends on bot mode
if self.mode == Mode.LIVE:
time.sleep(REPEAT_TIME[self.currentElectionStateHandler.edenBotMode])
elif self.mode == Mode.DEMO and self.modeDemo is not None:
# Mode.DEMO
LOG.debug("Demo mode: sleep time: " + str(10))
time.sleep(10) # in demo mode sleep 3
if self.modeDemo.isLiveMode():
self.modeDemo.setNextLiveBlockAndTimestamp()
else:
if self.modeDemo.isNextTimestampInLimit(seconds=60):
self.modeDemo.setNextTimestamp(seconds=60)
else:
LOG.success("Time limit reached - Demo mode finished")
break
else:
raise EdenBotException("Unknown Mode(LIVE, DEMO) or Mode.Demo and ModeDemo is None ")
# defines current election state and write it to the database
#just temp
#return
self.setCurrentElectionStateAndCallCustomActions(contract=eden_account, database=self.database)
except Exception as e:
LOG.exception("Exception in start loop. Description: " + str(e))
time.sleep(20)
except Exception as e:
LOG.exception("Exception: " + str(e))
raise EdenBotException("Exception: " + str(e))
def main():
print("------>Python<-------")
import sys
print("\nVersion: " + str(sys.version))
print("\n\n")
print("------>EdenBot<-------\n\n")
database = Database()
dfuseConnection = DfuseConnection(dfuseApiKey=dfuse_api_key, database=database)
edenData: EdenData = EdenData(dfuseConnection=dfuseConnection)
# testing
#data:
# CD of october 2022 elections: chrisbedenos, jesse.gem, marketing.gm, riekicordon1, xavieredenia
# change these CDs telegram to your own - to check if the process (all round) is working
# first round has 20 groups, second 5, third 1
# make sure that all groups are not created on time - to test if group is created live
# check if election number(continius) is correct, also check the year (in test mode will be current year,
# not election year)
# final group should be created in last 24 hours
# check if user is added to the group and if it has admin rights
# if user is not added automatically, add it manually and check if it gets admin rights
# start and finish group call - check if group gets messages by bot
# 5 and 10 minutes notifications should be sent to group and private
# when round is over there should be an message if group call is still running
# user bot should be removed from group after round is over (not bot, just user bot!)
# one day after election bot and user bot should be removed from CD group
startEndDatetimeList = [
#(datetime(2022, 6, 7, 11, 52), datetime(2022, 6, 7, 11, 53)), # just to add old election
#(datetime(2022, 10, 7, 11, 52), datetime(2022, 10, 7, 11, 59)), # add user
#(datetime(2022, 10, 7, 11, 59), datetime(2022, 10, 7, 12, 1)), # notification 25 hours before
#(datetime(2022, 10, 7, 12, 57), datetime(2022, 10, 7, 12, 58)), # adding users
#(datetime(2022, 10, 7, 12, 59), datetime(2022, 10, 7, 13, 2)), # notification - 24 hours before
#(datetime(2022, 10, 8, 11, 58), datetime(2022, 10, 8, 12, 2)), # notification - in one hour
#(datetime(2022, 10, 8, 12, 57), datetime(2022, 10, 8, 12, 59)), # notification - in few minutes
#(datetime(2022, 10, 8, 12, 59), datetime(2022, 10, 8, 13, 2)), # start
#(datetime(2022, 10, 8, 13, 51), datetime(2022, 10, 8, 13, 58)), # notification 10 and 5 min left
#(datetime(2022, 10, 8, 13, 59), datetime(2022, 10, 8, 14, 3)), # round 1 finished, start round 2
#(datetime(2022, 10, 8, 14, 51), datetime(2022, 10, 8, 14, 58)), # notification 10 and 5 min left
#(datetime(2022, 10, 8, 14, 59), datetime(2022, 10, 8, 15, 3)), # round 2 finished, start final round
#(datetime(2022, 10, 9, 12, 59), datetime(2022, 10, 9, 13, 2)), # one day after election ended
#(datetime(2022, 10, 15, 13, 0), datetime(2022, 10, 15, 13, 1)), # one week before video deadline
#(datetime(2022, 10, 20, 13, 0), datetime(2022, 10, 20, 13, 1)), # two days before video deadline
#(datetime(2022, 10, 21, 13, 0), datetime(2022, 10, 21, 13, 1)), # one day before video deadline
(datetime(2022, 10, 23, 13, 0), datetime(2022, 10, 23, 13, 1)), # 15 days after election remove bot from groups
#elections 6
#(datetime(2023, 4, 8, 13, 5), datetime(2023, 4, 8, 13, 6)), # round 1
#(datetime(2023, 4, 8, 17, 15), datetime(2023, 4, 8, 17, 18)), # after elections
]
# 120 blocks per minute
#modeDemo = ModeDemo(startAndEndDatetime=startEndDatetimeList,
# edenObj=edenData,
# step=1 # 1.5 min
# )
# live!
modeDemo = ModeDemo.live(edenObj=edenData,
stepBack=10)
EdenBot(edenData=edenData,
telegramApiID=telegram_api_id,
telegramApiHash=telegram_api_hash,
botToken=telegram_bot_token,
mode=Mode.DEMO,
database=database,
modeDemo=modeDemo).start()
while True:
time.sleep(1)
def runPyrogramTestMode(comm: Communication):
# database = Database()
# comm = Communication(database=database)
comm.idle()
def mainPyrogramTestMode():
# multiprocessing
database = Database()
comm = Communication(database=database)
comm.startComm(apiId=telegram_api_id, apiHash=telegram_api_hash, botToken=telegram_bot_token)
pyogram = Process(target=runPyrogramTestMode, args=(comm,))
pyogram.start()
i = 0
while True:
i = i + 1
# if i % 3 == 0:
if i == 3:
comm.sendMessage(chatId="", sessionType=SessionType.BOT, text="test")
time.sleep(3)
print("main Thread")
def main1():
database = Database()
election: Election = Election(electionID=10,
status=ElectionStatus(electionStatusID=7,
status=CurrentElectionState.CURRENT_ELECTION_STATE_REGISTRATION_V0),
date=datetime.now(),
contract=eden_account
)
comm = Communication(database=database)
comm.startComm(apiId=telegram_api_id, apiHash=telegram_api_hash, botToken=telegram_bot_token)
for i in range(0, 4):
for j in range(0, 25):
kva = Process(target=comm.sendMessage,
name="Pyrogram event handler",
args=(SessionType.BOT, "", "A:" + str(i) + " " + str(j))
)
kva.start()
comm.sendMessage(chatId="", sessionType=SessionType.BOT, text="B:" + str(i) + " " + str(j))
comm.sendMessage(chatId="", sessionType=SessionType.BOT, text="C:" + str(i) + " " + str(j))
comm.sendMessage(chatId="", sessionType=SessionType.BOT, text="test")
time.sleep(1)
#neki = await comm.isVideoCallRunning(sessionType=SessionType.BOT, chatId=)
#task = asyncio.get_event_loop().run_until_complete(comm.isVideoCallRunning(sessionType=SessionType.BOT,
# chatId=-1))
#kva =- 8
while True:
time.sleep(2)
if __name__ == "__main__":
main()
#main1()
# mainPyrogramTestMode() #to test pyrogram application - because of one genuine session file