-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
273 lines (228 loc) · 9.9 KB
/
bot.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
#!/usr/bin/python
# -*- coding: utf8 -*-
## POUR DCCRECEIVE ?
#from __future__ import print_function
import os
import struct
import irc.bot
import irc.strings
#from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
from config import *
import re
import random
def download(connection, nomRobot, numPaquet):
print("commande XDCC SEND #" + str(numPaquet) )
connection.notice(nomRobot, "xdcc send #" + str(numPaquet) )
def checkTerminated(bot, DL):
if DL.terminated == True :
bot.die()
################################################################################
# CLASS Grabator
################################################################################
class Grabator(irc.bot.SingleServerIRCBot):
"""
class Grabator
définit un bot qui se connecte à un serveur irc et est capable de
télécharger des paquets en xdcc.
Il peut scanner le topic du channel principal ainsi que les messages
privés afin de se connecter aux salons et channels de chat.
"""
def __init__(
self,
objetDL,
channel = ircDefaultChannel,
nickname = ircDefaultNickname,
server = ircDefaultServer,
numPaquet = ircDefaultNumPaquet,
nomRobot = ircDefaultNomRobot,
secondChannel = ircDefaultSecondChannel,
port = ircDefaultPort
):
print("channel =", channel, "; nickname =", nickname, "; server = ", server, port) #DEBUG
try:
irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
except:
print("bot.py : pb création bot/connexion server")
self.objetDL = objetDL
self.channel = channel
self.numPaquet = numPaquet
self.nomRobot = nomRobot
self.secondChannel = secondChannel
self.received_bytes = 0
self.ctcp_version = ircDefaultVersion
self.repriseDL = False
self.position = 0
# Pour gérer les encodages :
self.connection.buffer_class.encoding = 'utf-8'# self.connection.buffer_class. = irc.buffer.LineBuffer
# Execution retardée de l'envoi de la commande SEND (permettre connexion au second channel)
self.connection.execute_every(0.5, checkTerminated, (self, self.objetDL ) )
def on_nicknameinuse(self, c, event):
c.nick(c.get_nickname() + "_")
def on_welcome(self, connection, event):
connection.join(self.channel)
# pour gérer les problème d'encodage
self.connection.buffer.errors = 'replace'
if (self.secondChannel != ""):
print("connexion au secondChannel :", self.secondChannel)
connection.join(self.secondChannel)
# tempo et commande pour téléchargement
connection.execute_delayed(random.uniform(2,8), download, (connection, self.nomRobot, self.numPaquet) )
def on_privmsg(self, connection, event):
#DEBUG
print("priv --", event.arguments)
msgPriv = self.filtrerCouleur(event.arguments[0])
secondChannel = self.extraireChannel(msgPriv)
if ( secondChannel is not None ) :
if (secondChannel != self.channel):
self.secondChannel = secondChannel
print( "connexion au second channel : ", self.secondChannel)
connection.join(self.secondChannel)
else:
print( "Pas de channel dans le message privé")
def on_pubmsg(self, cconnection, event):
pass
#DEBUG
#print("pub ---", event.arguments)
def on_dccmsg(self, connection, event):
#DEBUG
#print("dccmsg --", event.arguments)
# Enregistrement dans le fichier des données reçues
data = event.arguments[0]
self.file.write(data)
self.received_bytes = self.received_bytes + len(data)
# synchro des infos avec le programme principal
self.objetDL.dejaTelechargeEnMo = (self.position + self.received_bytes)/1048576 # 1024*1024
self.objetDL.avancement = (self.position + self.received_bytes)/self.objetDL.tailleEnOctets*100
# Ack command ? part of DCC protocol ?
self.dcc.send_bytes(struct.pack("!I", self.received_bytes + self.position))
def on_dccchat(self, connection, event):
pass
def do_command(self, event, cmd):
pass
def on_ctcp(self, connection, event):
#DEBUG
print("on_ctcp --", event.arguments)
# Usefull info
nick = event.source.nick
# CTCP ANSWER TO : VERSION
if event.arguments[0] == "VERSION":
connection.ctcp_reply(nick, "VERSION " + self.ctcp_version)
# CTCP ANSWER TO : PING
elif event.arguments[0] == "PING":
if len(event.arguments) > 1:
connection.ctcp_reply(nick, "PING " + event.arguments[1])
# CTCP ANSWER TO : SEND => TELECHARGER
elif len(event.arguments) >= 2:
args = event.arguments[1].split()
if args[0] == "SEND":
self.filename = downloadPath + os.path.basename(args[1])
if os.path.exists(self.filename):
#DEBUG INFO :
print("A file named", self.filename,)
print("already exists. Attempting to resume it.")
# Récupère infos utiles
self.objetDL.tailleEnOctets = int(args[4])
self.peeraddress = irc.client.ip_numstr_to_quad(args[2])
self.position = os.path.getsize(self.filename)
# envoi commande resume
cmd = "DCC RESUME #"+ str(self.numPaquet) +" "+ str(args[3]) +" "+ str(self.position)
connection.ctcp_reply(self.nomRobot, cmd )
else:
# DEBUG INFO :
print("Pas de fichier existant. Debut du DL")
# récupération de la taille en Octets du fichier
self.objetDL.tailleEnOctets = int(args[4])
# création du fichier et connection DCC
self.file = open(self.filename, "wb")
peeraddress = irc.client.ip_numstr_to_quad(args[2])
peerport = int(args[3])
self.dcc = self.dcc_connect(peeraddress, peerport, "raw")
elif args[0] == "ACCEPT" :
# ouverture du fichier
print("on_ctcp RESUME")
self.file = open(self.filename, "ab")
peerport = int(args[2])
self.dcc = self.dcc_connect(self.peeraddress, peerport, "raw")
else:
# Error : (raising exception needed ?)
print("bot.py : error : dcc command incomprise")
self.die()
def on_dcc_disconnect(self, connection, event):
self.file.close()
print("Received file %s (%d bytes)." % (self.filename,
self.received_bytes))
print("Maintenant, je vais me coucher, ciao")
self.objetDL.status = "fini"
self.objetDL.avancement = 100
self.die()
def on_currenttopic(self, connection, event):
topic = self.filtrerCouleur(event.arguments[1])
secondChannel = self.extraireChannel(topic)
if ( secondChannel is not None ) :
if (secondChannel != self.channel):
self.secondChannel = secondChannel
print( "connexion au second channel : ", self.secondChannel)
connection.join(self.secondChannel)
else:
print( "Pas de channel dans le topic")
def filtrerCouleur(self, string):
return re.sub(
'(\\03..\,.)|(\\x03[0-9][0-9])|(\\x03[0-9])|(\\x03)|(\\x1f)|(\\x02)',
'',
string)
def extraireChannel(self, string) :
channel = re.findall('\#\S*',string)
if (channel == [] ):
return None
else :
return channel[0]
################################################################################
# CLASS Download
################################################################################
class Download :
def __init__(
self,
server = ircDefaultServer,
channel = ircDefaultChannel,
nomRobot = ircDefaultNomRobot,
numPaquet = ircDefaultNumPaquet,
nickname =ircDefaultNickname,
nomFichier = "Pas de nom défini",
secondChannel = ircDefaultSecondChannel,
port = ircDefaultPort
):
if server == "freenode":
self.server = "irc.freenode.net"
else:
self.server = "irc." + server + ".net"
self.channel = channel
self.nomRobot = nomRobot
self.numPaquet = numPaquet
self.nickname = nickname
self.secondChannel = secondChannel
self.nomFichier = nomFichier
self.port = port
# et pour le partage d'infos :
self.terminated = False
self.dejaTelechargeEnMo = 0
self.tailleEnOctets = 1048576
self.status = "pas commencé"
self.avancement = 0
def startDL(self):
self.status = "en cours"
self.pydccBot = Grabator(
self,
self.channel,
self.nickname,
self.server,
self.numPaquet,
self.nomRobot,
self.secondChannel,
self.port
)
self.pydccBot.start()
# TEST DE LA CLASSE GRABATOR, UN XDCC_BOT
if __name__ == "__main__":
print("bot.py - fonction test")
bot = Grabator()
bot.start()