Posted By

Keef on 02/03/10


Tagged

omegle


Versions (?)

Omegle class


 / Published in: Python
 

This is one of my first python programs so it's probably written very poorly...

Example use:

print 'Connecting to omegle...'
om = omegle()

if om.chatid:
    print 'Chatid: '+ om.chatid
else:
    if om.error:
        print om.error
    else:
        print 'No chatid given, we\'re possibly blocked.'

# Wait for our connection
while (not om.connected):
    om.getevents()
    sleep(0.5)

# Connected; Drop a message
om.send('HAI, ASL!? LOLO')

# Main loop, check for responses
while (om.connected):
    om.getevents()

    if not om.error:
        if om.message:
            print 'Stranger: ' + om.message
    else:
        print om.error

    sleep(0.5)
else:
    print 'Disconnecting...'
del om
  1. from urllib import urlencode
  2. from BaseHTTPServer import BaseHTTPRequestHandler
  3. import json
  4.  
  5. class omegle:
  6. """A class to interface directly with the Omegle website"""
  7.  
  8. # Global variables
  9. url = 'http://omegle.com'
  10. useragent = 'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)'
  11.  
  12. # Connection status
  13. connecting = False
  14. connected = False
  15.  
  16. # For Debugging/Error handling
  17. response = None
  18. error = None
  19.  
  20. # Partner status
  21. chatid = None
  22. message = None
  23. istyping = False
  24.  
  25.  
  26. def __init__(self):
  27. """Alias the connect function"""
  28. self.connect()
  29.  
  30. def connect(self):
  31. """Connect to the server and get a partners chat id"""
  32. self.chatid = str(self.getresponse('/start?rcs=1',{})).strip('"')
  33.  
  34. def getevents(self):
  35. """Poll the server for current events"""
  36.  
  37. # Clear any previous error messages
  38. self.error = None
  39.  
  40. self.message = False
  41. self.typing = False
  42.  
  43. self.response = json.loads(self.getresponse('/events', {'id': self.chatid}))
  44.  
  45. if self.response:
  46. for response in self.response:
  47. if response[0] == 'waiting':
  48. connecting = True
  49. elif response[0] == 'connected':
  50. connecting = False
  51. self.connected = True
  52. elif response[0] == 'gotMessage':
  53. # Sometimes it's possible to recieve a blank message
  54. if response[1]:
  55. # If messages aren't encoded the str function fails
  56. self.message = str(response[1].encode('utf-8'))
  57. elif response[0] == 'typing':
  58. self.istyping = True
  59. elif response[0] == 'stoppedTyping':
  60. self.istyping = False
  61. elif response[0] == 'strangerDisconnected':
  62. self.connected = False
  63. elif response[0] == 'recaptchaRequired':
  64. self.connected = False
  65. self.error = 'Omegle\'s asking for a captcha.'
  66. else:
  67. # Fallback for debugging if a command isn't recognised
  68. self.error = 'Command not recognised: ' + response[0]
  69. return self.error
  70.  
  71. def send(self, message):
  72. """Send a message
  73.  
  74. Keyword arguments:
  75. message -- The message to send.
  76. """
  77.  
  78. self.response = self.getresponse('/send', {'id': self.chatid, 'msg': message})
  79. if (self.response == 'fail'):
  80. self.error = 'Failed to send message: "' + str(message) + '".'
  81.  
  82. def typing(self):
  83. """Indicate to the server the client's typing"""
  84. self.getresponse('/typing', {'id': self.chatid})
  85.  
  86. def stoppedTyping(self):
  87. """Indicate to the server the client's stopped typing"""
  88. self.getresponse('/stoppedTyping', {'id': self.chatid})
  89.  
  90. def disconnect(self):
  91. """Indicate to the server the client's disconnected"""
  92. self.getresponse('/disconnect', {'id': self.chatid})
  93. self.connected = False
  94.  
  95. def getresponse(self, url, data=None):
  96. """Send data to the server and return the result.
  97.  
  98. Keyword arguments:
  99. url -- The url for the page we're getting (relative to self.url).
  100. data -- Optional data to post to the server.
  101. """
  102. self.error = None
  103.  
  104. try:
  105. # Setup the page request
  106. request = Request(self.url + url)
  107. request.add_header('User-agent', self.useragent)
  108.  
  109. # Have we got data to POST?
  110. if data is not None:
  111. request.add_data(urlencode(data))
  112.  
  113. return urlopen(request).read()
  114. except URLError, e:
  115. # Is our error HTTP or URL based?
  116. if hasattr(e, 'reason'):
  117. self.error = 'Cannot retrieve URL:' + e.reason[1]
  118. elif hasattr(e, 'code'):
  119. self.error = 'Cannot retrieve URL:' + str(e.code) + BaseHTTPRequestHandler.responses[e.code][0]
  120.  
  121. def __del__(self):
  122. """Alias the disconnect function"""
  123. self.disconnect()

Report this snippet  

You need to login to post a comment.