-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.py
303 lines (272 loc) · 12.3 KB
/
app.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
import requests
from requests_oauthlib import OAuth1
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import settings
import json
import threading
import time
import mysql.connector
import traceback
from logging import getLogger, StreamHandler, DEBUG
logger = getLogger(__name__)
handler = StreamHandler()
handler.setLevel(DEBUG)
logger.setLevel(DEBUG)
logger.addHandler(handler)
logger.propagate = False
class XP_RPC():
def __init__(self):
self.connection = AuthServiceProxy(
settings.RPC_URL % (settings.rpc_user, settings.rpc_password))
self.tax = 1.0
def get_address(self, name):
# commands = [["getaddressesbyaccount", name]]
address = self.connection.getaddressesbyaccount(name)
if address:
address = address[0]
else:
address = self.connection.getaccountaddress(name)
return address
def show_balance(self, name):
address = self.connection.getaddressesbyaccount(name)
if address:
balance = self.connection.getbalance(name)
else:
address = self.connection.getaccountaddress(name)
balance = self.connection.getbalance(name)
print(balance)
return balance
def move_balance(self, name, to_name, amount):
address = self.connection.getaddressesbyaccount(name)
to_address = self.connection.getaddressesbyaccount(to_name)
if address and to_address:
# req = self.connection.move(name, to_name, amount)
req = self.connection.move(name, to_name, amount)
elif address:
self.connection.getaccountaddress(to_name)
req = self.connection.move(name, to_name, amount)
else:
req = "Error"
return req
def send_from(self, name, address, amount):
txid = self.connection.sendfrom(name, address, amount)
tx = self.connection.gettransaction(txid)
if tx:
fee = tx["fee"]
else:
fee = 0
self.move_balance(name, "taxpot", float(fee) + self.tax)
return txid
def validateaddress(self, address):
return self.connection.validateaddress(address)['isvalid']
class Twitter():
def __init__(self):
self.xpd = XP_RPC()
self.auth_stream = OAuth1(settings.CONSUMER_KEY_STREAM, settings.CONSUMER_SECRET_STREAM,
settings.ACCESS_TOKEN_STREAM, settings.ACCESS_TOKEN_SECRET_STREAM)
self.auth_reply = OAuth1(settings.CONSUMER_KEY_REPLY, settings.CONSUMER_SECRET_REPLY,
settings.ACCESS_TOKEN_REPLY, settings.ACCESS_TOKEN_SECRET_REPLY)
self.tweets = []
self.conn = mysql.connector.connect(
user=settings.dbuser, password=settings.dbpass, host=settings.dbhost, database=settings.dbname)
self.cur = self.conn.cursor()
def reply(self, text, reply_token):
params = {
"status": text,
"in_reply_to_status_id": reply_token,
"auto_populate_reply_metadata": "true"
}
req = requests.post(
"https://api.twitter.com/1.1/statuses/update.json", auth=self.auth_reply, data=params)
return req
def detect(self, tweet):
print("Detecting...")
m = tweet["text"].split()
logger.debug(m)
idx = 0
commands = ["tip", "deposit", "balance",
"withdraw", "withdrawall", "donate"]
if m[idx] == "@tip_XPchan":
command = m[idx + 1]
if command == "@tip_XPchan":
command = m[idx + 2]
idx += 1
elif command not in commands:
if m[idx + 2] == "@tip_XPchan":
command = m[idx + 3]
idx += 2
lang = tweet["user"]["lang"]
address_name = "tipxpchan-" + tweet["user"]["id_str"]
if command == "tip":
print("tip in")
amount = m[idx + 3]
if m[idx + 2][0] == "@":
to_name = "tipxpchan-" + self.get_id(m[idx + 2][1:])
balance = self.xpd.show_balance(address_name)
amount = float(amount)
if balance >= amount:
if self.xpd.move_balance(address_name, to_name, amount):
if lang == "ja":
text = "XPちゃんより%sさんにお届けものだよっ! %fXP\n『@tip_XPchan balance』で残高確認が行えるよ!" % (
m[idx + 2], amount)
else:
text = "Present for %s! Sent %fXP!" % (
m[idx + 2], amount)
try:
if "#XPちゃんねる" in m:
service = "xpchannnel"
elif "#XPのべる" in m:
service = "xpnovel"
self.cur.execute("insert into tip_history (tipfrom, tipto, amount, service) values (%s, %s, %s, %s)", (
tweet["user"]["screen_name"], m[idx + 2][1:], amount, service))
self.conn.commit()
req = self.reply(text, tweet["id"])
except:
print(traceback.format_exc())
req = self.reply(text, tweet["id"])
else:
if lang == "ja":
text = "残高が足りないよ〜 所持XP:%f" % balance
else:
text = "Not enough balance! XP:%f" % balance
req = self.reply(text, tweet["id"])
else:
print("エラーだよっ!よく確認してね!")
elif command == "donate":
print("donate in")
amount = m[idx + 2]
to_name = "tipxpchan-940589020509192193"
balance = self.xpd.show_balance(address_name)
amount = float(amount)
if balance >= amount:
if self.xpd.move_balance(address_name, to_name, amount):
if lang == "ja":
text = "@%s 開発へのご支援ありがとうございます!" % tweet["user"]["name"]
else:
text = "@%s Thank you for donation!" % tweet["user"]["name"]
req = self.reply(text, tweet["id"])
else:
if lang == "ja":
text = "残高が足りないよ〜 所持XP:%f" % balance
else:
text = "Not enough balance! XP:%f" % balance
req = self.reply(text, tweet["id"])
elif command == "deposit":
print("deposit in")
if lang == "ja":
text = "%sさんのアドレスは「%s」だよっ!" % (
tweet["user"]["name"], self.xpd.get_address(address_name))
else:
text = "%s 's address is 「%s」!" % (
tweet["user"]["name"], self.xpd.get_address(address_name))
req = self.reply(text, tweet["id"])
elif command == "withdraw":
print("withdraw in")
amount = m[idx + 3]
balance = self.xpd.show_balance(address_name)
amount = float(amount)
address = m[idx + 2]
if balance >= amount + self.xpd.tax:
if self.xpd.validateaddress(address):
txid = self.xpd.send_from(
address_name, address, amount)
if lang == "ja":
text = """
「%s」に%fXPを引き出したよ!(手数料:%dXP)\nhttps://chainz.cryptoid.info/xp/tx.dws?%s.htm
""" % (address, amount, self.xpd.tax, txid)
else:
text = """
Withdraw Complete! Sent %fXP to [%s]!(Fee:%dXP)\nhttps://chainz.cryptoid.info/xp/tx.dws?%s.htm
""" % (address, amount, txid)
req = self.reply(text, tweet["id"])
else:
if lang == "ja":
text = "ごめんなさい!アドレスが間違ってるみたいだよ!"
else:
text = "Invalid Address!"
req = self.reply(text, tweet["id"])
else:
if lang == "ja":
text = "残高が足りないよ〜 所持XP:%f\n引き出しには手数料の%dXPがかかるよ!" % (
balance, self.xpd.tax)
else:
text = "Not enough balance! XP:%f\nPlease note that required %dXP fee when withdraw" % (
balance, self.xpd.tax)
req = self.reply(text, tweet["id"])
elif command == "withdrawall":
print("withdrawall in")
balance = self.xpd.show_balance(address_name)
amount = float(balance) - self.xpd.tax
address = m[idx + 2]
if self.xpd.validateaddress(address):
txid = self.xpd.send_from(
address_name, address, amount)
if lang == "ja":
text = """
「%s」に%fXPを引き出したよ!(手数料:%dXP)\nhttps://chainz.cryptoid.info/xp/tx.dws?%s.htm
""" % (address, amount, self.xpd.tax, txid)
else:
text = """
Withdraw Complete! Sent %fXP to [%s]!(Fee:%dXP)\nhttps://chainz.cryptoid.info/xp/tx.dws?%s.htm
""" % (address, amount, self.xpd.tax, txid)
req = self.reply(text, tweet["id"])
else:
if lang == "ja":
text = "ごめんなさい!アドレスが間違ってるみたいだよ!"
else:
text = "Invalid Address!"
req = self.reply(text, tweet["id"])
elif command == "balance":
print("balance in")
if lang == "ja":
text = "%sさんの保有XPは%fXPだよん!" % (
tweet["user"]["name"], self.xpd.show_balance(address_name))
else:
text = "%s 's balance is %fXP!" % (
tweet["user"]["name"], self.xpd.show_balance(address_name))
req = self.reply(text, tweet["id"])
else:
print("command error")
# text = "エラーだよっ!よく確認してね!"
# req = self.reply(text, tweet["id"])
else:
pass
def get_id(self, name):
params = {
"screen_name": name,
}
user_id = requests.get("https://api.twitter.com/1.1/users/show.json",
auth=self.auth_reply, params=params).json()["id_str"]
return user_id
def collect():
url = "https://stream.twitter.com/1.1/statuses/filter.json"
# twitter = Twitter()
# print(twitter.detect(tweet))
_stream = requests.post(url, auth=twitter.auth_stream,
stream=True, data={"track": "@tip_XPchan"})
for _line in _stream.iter_lines():
try:
_doc = json.loads(_line.decode("utf-8"))
if _doc:
twitter.tweets.append(_doc)
else:
pass
except:
# print("エラー")
pass
def job():
while True:
try:
twitter.detect(twitter.tweets.pop(0))
# print(twitter.tweets)
time.sleep(30)
except:
time.sleep(1)
# print(traceback.format_exc())
continue
if __name__ == '__main__':
twitter = Twitter()
thread_1 = threading.Thread(target=collect)
thread_2 = threading.Thread(target=job)
thread_1.start()
thread_2.start()