Logging in as user using discord.py - python-3.x

I am trying to make some simple program, showing received messages through the terminal. Now I am trying to ask the user for their email address and password for the login, but some errors occur, which I do not quite understand. This is what my code looks like:
import discord
class DiscordClient(discord.Client):
def __init__(self, *args, **kwargs):
discord.Client.__init__(self, **kwargs)
async def on_ready(self):
print('Success!')
if __name__ == '__main__':
dc = DiscordClient()
dc.login(input('email : '), input('password : '), bot=False)
dc.run()
and the error is:
Traceback (most recent call last):
File "[...]/Main.py", line 16, in <module>
dc.run()
File "[...]/lib/python3.6/site-packages/discord/client.py", line 519, in run
self.loop.run_until_complete(self.start(*args, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 466, in run_until_complete
return future.result()
File "[...]/lib/python3.6/site-packages/discord/client.py", line 490, in start
yield from self.login(*args, **kwargs)
File "[...]/lib/python3.6/site-packages/discord/client.py", line 418, in login
raise TypeError('login() takes 1 or 2 positional arguments but {} were given'.format(n))
TypeError: login() takes 1 or 2 positional arguments but 0 were given
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x103881fd0>
So, what am I doing wrong, or what should code look like? All I was doing was write an on_message() and some basic commands like send_message().

client.login is a coroutine so it should be (untested) :
await dc.login(input('email : '), input('password : '), bot=False)
Note that in this case, bot parameter is not needed.
However, to use client.login, you need to use the client loop. To avoid that, you can simply do:
dc.run(email, password)
Which will both login and connect and then start the loop.
After that you can (in the on_ready function) get a desired server from dc.servers and a suitable channel to send there, for example, a 'Hello message' with dc.send_message.
When you are done with the connection, do self.close() from within the DiscordClient class.
Working example for Python 3.4 (replace keywords as necessary for Python 3.6)
import discord
import asyncio
import datetime
class DiscordClient(discord.Client):
def __init__(self, *args, **kwargs):
discord.Client.__init__(self, **kwargs)
#asyncio.coroutine
def on_ready(self):
servers = list(self.servers)
for server in servers:
if server.name == 'My server':
break
for channel in server.channels:
if channel.name == 'general':
break
now = datetime.datetime.now()
yield from self.send_message(channel, 'Api Success! at ' + str(now))
print('Success!')
yield from self.close()
if __name__ == '__main__':
dc = DiscordClient()
email = input('email : ')
password = input('password : ')
dc.run(email, password)

Related

How to use timeout to stop blocking function subscribe.simple

I want to use timeout to stop the blocking function of mqtt, I use a the timeout_decorator module, it can stop command function but cannot stop blocking function, subscribe.simple.
The following code runs successfully
import time
import timeout_decorator
#timeout_decorator.timeout(5, timeout_exception=StopIteration)
def mytest():
print("Start")
for i in range(1,10):
time.sleep(1)
print("{} seconds have passed".format(i))
if __name__ == '__main__':
mytest()
the result as follow:
Start
1 seconds have passed
2 seconds have passed
3 seconds have passed
4 seconds have passed
Traceback (most recent call last):
File "timeutTest.py", line 12, in <module>
mytest()
File "/home/gyf/.local/lib/python3.5/site-packages/timeout_decorator/timeout_decorator.py", line 81, in new_function
return function(*args, **kwargs)
File "timeutTest.py", line 8, in mytest
time.sleep(1)
File "/home/gyf/.local/lib/python3.5/site-packages/timeout_decorator/timeout_decorator.py", line 72, in handler
_raise_exception(timeout_exception, exception_message)
File "/home/gyf/.local/lib/python3.5/site-packages/timeout_decorator/timeout_decorator.py", line 45, in _raise_exception
raise exception()
timeout_decorator.timeout_decorator.TimeoutError: 'Timed Out'
but I failed with the subscribe.simple API
import timeout_decorator
#timeout_decorator.timeout(5)
def sub():
# print(type(msg))
print("----before simple")
# threading.Timer(5,operateFail,args=)
msg = subscribe.simple("paho/test/simple", hostname=MQTT_IP,port=MQTT_PORT,)
print("----after simple")
return msg
publish.single("paho/test/single", "cloud to device", qos=2, hostname=MQTT_IP,port=MQTT_PORT)
try:
print("pub")
msg = sub()
print(msg)
except StopIteration as identifier:
print("error")
The result infinitely wait
pub
----before simple
I want the function which include subscribe.simple API can stop after 5 seconds.
Asyncio won't be able to handle blocking function in the same thread. therefore using asyncio.wait_for failed. However, inspired by this blog post I used loop.run_in_executor to keep control on the blocking thread.
from paho.mqtt import subscribe
import asyncio
MQTT_IP = "localhost"
MQTT_PORT = 1883
msg = None
def possibly_blocking_function():
global msg
print("listenning for message")
msg = subscribe.simple(
"paho/test/simple",
hostname=MQTT_IP,
port=MQTT_PORT,
)
print("message received!")
async def main():
print("----before simple")
try:
await asyncio.wait_for(
loop.run_in_executor(None, possibly_blocking_function), timeout=5
)
except asyncio.TimeoutError:
pass
print("----after simple")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Output :
----before simple
listenning for message
----after simple
Please note this is not perfect, the program won't end since there are running tasks. You can exit it using various solution but this is out of scope since I am still looking for a clean way to close that stuck thread.

TypeError in number of arguments passed to the _target()

I want to run a method (speak) in a separate thread in python. Here is my code,
import threading
class Example:
def instruct(self, message_type):
instruction_thread = threading.Thread(target=self.speak, args=message_type)
instruction_thread.start()
def speak(self, message_type):
if message_type == 'send':
print('send the message')
elif message_type == 'inbox':
print('read the message')
e = Example()
e.instruct('send')
But I get following error,
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\envs\talkMail\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\ProgramData\Anaconda3\envs\talkMail\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
TypeError: speak() takes 2 positional arguments but 5 were given
What is the reason for this? can anyone clarify?
From the docs: https://docs.python.org/3/library/threading.html#threading.Thread
args is the argument tuple for the target invocation. Defaults to ().
So instead of passing the argument as a string like you are doing right now, you want to pass it as a tuple like args=(message_type,).
Once you do that the code works fine
import threading
class Example:
def instruct(self, message_type):
#Pass message_type as tuple
instruction_thread = threading.Thread(target=self.speak, args=(message_type,))
instruction_thread.start()
def speak(self, message_type):
if message_type == 'send':
print('send the message')
elif message_type == 'inbox':
print('read the message')
e = Example()
e.instruct('send')
The output is
send the message

Discord bot.py file unable to load extensions [discord.py rewrite]

I've run into an issue with switching to the rewrite of discord.py. On extension loading I'm running into an ExtensionNotFound error.
I've tried different methods to get the extension to be recognized (such as using the entire directory in the code to find the folder containing cogs). Unfortunately all methods I've tried have resulted in the same ExtensionNotFound error.
Methods I've tried:
STARTUP = ['cogsR.basic_repliesR']
cogs_dir = r'D:\Code-Dev\Pyhthon\DiscordStuff\Bots\ri0tbot\ri0t-bot_current_v(rewrite)\cogsR'
if __name__ == '__main__':
for extension in [f.replace('.py', '') for f in listdir(cogs_dir) if isfile(join(cogs_dir, f))]:
try:
bot.load_extension(cogs_dir + "." + extension)
except (d.ClientException, ModuleNotFoundError):
print(f'Failed to load extension {extension}.')
traceback.print_exc()
STARTUP = ['cogR.basic_repliesR']
if __name__ == '__main__':
sys.path.insert(1, os.getcwd() + '/cogsR/')
for extension in STARTUP:
try:
bot.load_extension(extension)
except (AttributeError, ImportError) as e:
exc = '{}: {}'.format(type(e).__name__, e)
cprint('extension error {}\n{}'.format(extension, exc), 'red')
Through either of these methods the bot.py file should have been able to load the extensions in the STARTUP library. Instead I'm met with the following error message on file run.
Exception has occurred: ExtensionNotFound
Extension 'cogsR.basic_repliesR' could not be loaded.
File "C:\Users\edmun\AppData\Local\Programs\Python\Python36\Lib\site-packages\discord\ext\commands\bot.py", line 620, in load_extension
raise errors.ExtensionNotFound(name, e) from e
File "D:\Code-Dev\Pyhthon\discordstuff\Bots\ri0tbot\ri0t-bot_current_v(rewrite)\botR.py", line 50, in <module>
bot.load_extension(extension)
File "C:\Users\edmun\AppData\Local\Programs\Python\Python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\edmun\AppData\Local\Programs\Python\Python36\Lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Users\edmun\AppData\Local\Programs\Python\Python36\Lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
'''cog: commands using a list for randomly chosen replies'''
from random import choice
import asyncio
import os
import discord as d
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
from utilitiesR import lists
class ListCommands(commands.Cog):
def __init__(self, bot, **kwargs):
self.bot = bot
self.name = kwargs.get('username')
#commands.command(pass_context=True)
async def rip(self, ctx):
'''a basic rip command'''
#await ctx.send_typing()
#await asyncio.sleep(0.3)
_choice = choice(lists.RIP)
await ctx.send(_choice)
def setup(bot):
'''cog setup'''
bot.add_cog(ListCommands(bot))
print('list commands ready')
Try This.
if __name__ == '__main__':
for cog in os.listdir("./cogsR"):
if cog.endswith(".py"):
try:
cog = f"cogs.{cog.replace('.py', '')}"
bot.load_extension(cog)
except Exception as e:
print(f"{cog} Can not be loaded")
raise e
else:
print("{} has been succesfully Loaded.".format(cog))

Python Multiprocessing - TypeError: Pickling an AuthenticationString

I am making a python script that initially created threads and used them to brute force port 22 on my local machine using a wordlist, part of an infosec project.
I had issues when there were too many threads and I wanted to kill them off elegantly and exit the program and so I started to look at multiprocessing instead based this post's answer by by user cfi.
The problem I have is that when I run the program I am getting the below error.
python3 ssh_brute.py
[*] Pass not found
Traceback (most recent call last):
File "/Users/richardcurteis/anaconda3/lib/python3.7/multiprocessing/queues.py", line 236, in _feed
obj = _ForkingPickler.dumps(obj)
File "/Users/richardcurteis/anaconda3/lib/python3.7/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
File "/Users/richardcurteis/anaconda3/lib/python3.7/multiprocessing/process.py", line 330, in __reduce__
'Pickling an AuthenticationString object is '
TypeError: Pickling an AuthenticationString object is disallowed for security reasons
I assume I am doing something wrong with the multiprocessing API but I am not sure what exactly. I have looked at the docs and I believe I am more or less on track.
What am I missing?
Code:
import paramiko
from multiprocessing import Queue, Process
TARGET_IP = 'localhost'
USERNAME = 'richardcurteis'
WORDLIST = 'test2.txt'
MAX_THREADS = 10
processes = []
found = []
q = Queue()
def ssh_connect(target_ip, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
ssh.connect(target_ip, username=username, password=password)
found.append(password)
q.put(password)
except paramiko.ssh_exception.AuthenticationException:
print("[*] Failed: ", password)
return False
finally:
ssh.close()
return True
def close_threads(abort=False):
for p in processes:
p.join()
if abort:
for x in processes:
x.terminate()
processes.clear()
def main():
with open(WORDLIST) as input_handle:
process_count = 0
for line in input_handle:
try:
password = line.rstrip()
p = Process(target=ssh_connect, args=[TARGET_IP, USERNAME, password])
processes.append(p)
p.start()
q.put(p)
process_count += 1
if not q.empty():
break
if process_count >= MAX_THREADS:
close_threads()
process_count = 0
except KeyboardInterrupt:
print("[!] Interrupted by user")
break
except (ConnectionResetError, paramiko.ssh_exception.SSHException):
print("[X] Connection reset by target. Reduce thread count")
break
close_threads()
if len(found) > 0:
for c in found:
print("[!] Found: ", c)
else:
print("[*] Pass not found")
if __name__ == '__main__':
main()

Python - Multiprocessing Pool map returning can't pickle error

I have following code which creates a testrail client and executes testrail's GET_SUITES API call.
I have a function to call the GET_SUITES API and I am passing testrail client & test_rail_project_id as params
I am trying to use multiprocessing to execute over my list of projects to speed up things and I am can't pickle error
My code:
from itertools import product
def get_suites(client, project_id):
try:
path = 'get_suites/{projectid}'.format(projectid=project_id)
test_rail_response = client.send_get(path)
return test_rail_response
except Exception as e:
raise Exception(str(e))
if __name__ == "__main__":
testRailClient = APIClient(TESTRAIL_URL)
pool = Pool(2)
all_project_ids = [100, 200, 300]
data = pool.starmap(get_suites, product([testRailClient], all_project_ids))
Error stack:
Traceback (most recent call last):
File "main.py", line 57, in <module>
data = pool.starmap(testrailapi.get_suites, product([testRailClient], all_project_ids))
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 274, in starmap
return self._map_async(func, iterable, starmapstar, chunksize).get()
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 644, in get
raise self._value
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 424, in _handle_tasks
put(task)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: can't pickle SSLContext objects
Any suggestions please?
Thank you
PS: I am using Python3.6
UPDATE:
As suggested I tried removing the API client as a parameter and it worked but I am getting the same error when I have "get_suites" as a method. Please see my updated code below
class TestRailExecution:
def __init__(self, url, username, password):
self.url = url
self.username = username
self.password = password
self.client = APIClient(self.url)
self.client.user = username
self.client.password = password
def get_suites(self, project_id):
try:
path = 'get_suites/{projectid}'.format(projectid=project_id)
test_rail_response = self.client.send_get(path)
return test_rail_response
except Exception as e:
raise Exception(str(e))
if __name__ == "__main__":
testRailClient = TestRailExecution(TESTRAIL_URL, user, password)
pool = Pool(2)
data = pool.map(get_suites, [100, 200, 300])

Resources