kertser commited on
Commit
321551d
·
1 Parent(s): 905f4ca

Upload WarOnline_Chat_test.py

Browse files
Files changed (1) hide show
  1. WarOnline_Chat_test.py +211 -0
WarOnline_Chat_test.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is an quote and post library for a specific thread in the WarOnline forum.
2
+
3
+ import WarClient
4
+ import requests
5
+ import re
6
+ from bs4 import BeautifulSoup
7
+ import urllib.request as urllib
8
+ import warnings
9
+ import schedule
10
+ import time
11
+ from tqdm import tqdm
12
+ warnings.filterwarnings("ignore")
13
+
14
+ # Define the login URL and the thread URL
15
+ login_url = 'https://waronline.org/fora/index.php?login/login'
16
+ thread_url = 'https://waronline.org/fora/index.php?threads/warbot-playground.17636/'
17
+ post_url = "https://waronline.org/fora/index.php?threads/warbot-playground.17636/add-reply"
18
+
19
+ # Sending the message (change that!)
20
+ message = "Test"
21
+
22
+ # Define the login credentials
23
+ username = 'WarBot'
24
+ password = 'naP2tion'
25
+
26
+ # Start a session to persist the login cookie across requests
27
+ session = requests.Session()
28
+
29
+
30
+ def compare_pages(url1, url2):
31
+ #Compares 2 pages and returns True if they are the same
32
+ return urllib.urlopen(url1).geturl() == urllib.urlopen(url2).geturl()
33
+
34
+ def login(username=username, password=password, thread_url=thread_url):
35
+ # Log-In to the forum and redirect to thread
36
+
37
+ # Retrieve the login page HTML to get the CSRF token
38
+ login_page_response = session.get(login_url)
39
+ soup = BeautifulSoup(login_page_response.text, 'html.parser')
40
+ csrf_token = soup.find('input', {'name': '_xfToken'})['value']
41
+
42
+ # Login to the website
43
+ login_data = {
44
+ 'login': username,
45
+ 'password': password,
46
+ 'remember': '1',
47
+ '_xfRedirect': thread_url,
48
+ '_xfToken': csrf_token
49
+ }
50
+ response = session.post(login_url, data=login_data)
51
+
52
+ # Check if the login was successful
53
+ if 'Invalid login' in response.text:
54
+ print('Login failed!')
55
+ exit()
56
+
57
+ def post(message=message, thread_url=thread_url, post_url=post_url, quoted_by="",quote_text="",quote_source=""):
58
+ #Post a message to the forum (with or without the quote
59
+ #quote_source is in format 'post-3920992'
60
+ quote_source = quote_source.split('-')[-1] # Take the numbers only
61
+
62
+ if quoted_by:
63
+ message = f'[QUOTE="{quoted_by}, post: {quote_source}"]{quote_text}[/QUOTE]{message}'
64
+ #message = f'[QUOTE="{quoted_by}, data-source=post: {quote_source}"]{quote_text}[/QUOTE]{message}'
65
+ # optionally add @{quoted_by} to indent the quoter
66
+
67
+ # Retrieve the thread page HTML
68
+ response = session.get(thread_url)
69
+
70
+ # Parse the HTML with BeautifulSoup
71
+ soup = BeautifulSoup(response.text, 'html.parser')
72
+
73
+ # Extract the _xfToken value from the hidden form field
74
+ xf_token = soup.find('input', {'name': '_xfToken'}).get('value')
75
+
76
+ # Construct the message data for the POST request
77
+ message_data = {
78
+ '_xfToken': xf_token,
79
+ 'message': message,
80
+ 'attachment_hash': '',
81
+ 'last_date': '',
82
+ '_xfRequestUri': post_url,
83
+ '_xfWithData': '1',
84
+ '_xfResponseType': 'json'
85
+ }
86
+
87
+ response = session.post(post_url, data=message_data)
88
+
89
+ # Check if the post was successful
90
+ if not response.ok:
91
+ print('Post failed!')
92
+ exit()
93
+
94
+ print('Post submitted successfully.')
95
+
96
+ def messagesByUser(thread_url=thread_url, username="", startingPage=1):
97
+ # Returns all the quotes for #username in the specific multi-page thread url
98
+ allquotes =[]
99
+
100
+ page = startingPage # Counter
101
+ lastPage = False
102
+
103
+ # Initial values for messangerName and the message ID
104
+ messengerName = ""
105
+ messageID = ""
106
+ quotedID = ""
107
+
108
+ # Patterns to search in the last quote.
109
+ namePattern = re.compile('data-lb-caption-desc="(.*?) ·')
110
+ messageIDPattern = re.compile('data-lb-id="(.*?)"')
111
+ quotedIDPattern = re.compile('data-source="(.*?)"')
112
+
113
+ while not lastPage:
114
+ response = requests.get(thread_url + 'page-' + str(page))
115
+ if response.status_code == 200:
116
+
117
+ # Core of the function
118
+ html_content = response.content
119
+
120
+ # Parse the HTML content using BeautifulSoup
121
+ soup = BeautifulSoup(html_content, 'html.parser')
122
+
123
+ # Find all the message in the thread page
124
+ messageData = soup.find_all('div', {'class': 'message-userContent lbContainer js-lbContainer'})
125
+
126
+ for data in messageData:
127
+
128
+ if (username) in data.text:
129
+ try:
130
+ # Get the messager username
131
+ matchName = namePattern.search(str(data))
132
+ if matchName:
133
+ messengerName = matchName.group(1)
134
+
135
+ # Get the quoted ID
136
+ matchID = quotedIDPattern.search(str(data))
137
+ if matchID:
138
+ quotedID = matchID.group(1)
139
+
140
+ # Get the message ID
141
+ matchID = messageIDPattern.search(str(data))
142
+ if matchID:
143
+ messageID = matchID.group(1)
144
+
145
+ # Make sure that the messages have a quote inside
146
+ blockquote = data.find('blockquote')
147
+ if blockquote:
148
+ # Extract the text
149
+ text = data.find('div', {'class': 'bbWrapper'})
150
+ for bq in text.find_all('blockquote'):
151
+ bq.extract()
152
+ reply = text.get_text().replace('\n', ' ').strip()
153
+
154
+ allquotes.append({'reply': reply, 'messengerName': messengerName, 'messageID': messageID, 'quotedID': quotedID})
155
+
156
+ except:
157
+ continue # There was no text in quote, move next
158
+
159
+ #check if that is not a last page
160
+ if not compare_pages(thread_url + 'page-' + str(page), thread_url + 'page-' + str(page + 1)):
161
+ page += 1
162
+ else:
163
+ lastPage = True
164
+ else:
165
+ lastPage = True
166
+
167
+ return allquotes
168
+ def WarOnlineBot():
169
+ # Get All Quotes by all users
170
+ allMessages = messagesByUser(thread_url=thread_url, username="", startingPage=1)
171
+ botMessages = messagesByUser(thread_url=thread_url, username=username, startingPage=1)
172
+ for quote in quotes:
173
+ pass
174
+
175
+ message = ""
176
+ if not replies: # Meaning that there are no answers
177
+ while not message:
178
+ message = WarClient.getReply(message=quote['reply'])
179
+ print('Quote: ', quote['reply'])
180
+ print('Reply: ',message)
181
+ # post(message=message, thread_url=thread_url, post_url=post_url, quoted_by=quote['messengerName'],
182
+ # quote_text=quote['reply'], quote_source = quote['messageID'].split(":")[-1].strip())
183
+ print('posted the message to the forum')
184
+ time.sleep(5) # Standby time for server load release
185
+
186
+ if __name__ == '__main__':
187
+ timeout = 2 # min
188
+
189
+ login(username=username, password=password, thread_url=thread_url)
190
+ print("logged in")
191
+
192
+ ### Disabled. Will be enabled later on ###
193
+ #post(message=message, thread_url=thread_url, post_url=post_url, quoted_by='Василий Пупкин', quote_text='quoted message', quote_source='3926006')
194
+
195
+ quotes = messagesByUser(username=username)
196
+ for quote in quotes:
197
+ print(quote)
198
+
199
+ """
200
+ # Start the scheduler
201
+ while True:
202
+ login(username=username, password=password, thread_url=thread_url)
203
+ print("logged in")
204
+ WarOnlineBot()
205
+ p_bar = tqdm(range(60 * timeout))
206
+
207
+ for i in p_bar:
208
+ p_bar.update(1)
209
+ p_bar.refresh()
210
+ time.sleep(1)
211
+ """