Giter Club home page Giter Club logo

discord-s.c.u.m's Introduction

merubokkusu github stats

Q: Are you still active? I dont see any recent commits.

A: I do a lot of private repo work.

discord-s.c.u.m's People

Contributors

akbar-amin avatar balam314 avatar caiocinel avatar chronobrake avatar disconsolance avatar djj05 avatar dolfies avatar ericz avatar gabrielmajosi avatar gilgames000 avatar gokhancelikkaya avatar hattorius avatar imshvishal avatar lyfhael avatar merubokkusu avatar puv avatar scr33m avatar uiynyny avatar vivinano avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

discord-s.c.u.m's Issues

Status not setting

Hi its me again! Basically when I call clients.setStatus(0) nothing happens. The user does not go online, and I get the response - (<discum.user.user.User->setStatus) Response <- {"locale": "en-US", "show_current_game": true, "restricted_guilds": [], "default_guilds_restricted": false, "inline_attachment_media": true, "inline_embed_media": true, "gif_auto_play": true, "render_embeds": true, "render_reactions": true, "animate_emoji": true, "enable_tts_command": true, "message_display_compact": false, "convert_emoticons": true, "explicit_content_filter": 1, "disable_games_tab": false, "theme": "dark", "developer_mode": false, "guild_positions": [], "detect_platform_accounts": true, "status": "online", "afk_timeout": 600, "timezone_offset": 600, "stream_notifications_enabled": true, "allow_accessibility_detection": false, "contact_sync_enabled": false, "native_phone_integration_enabled": true, "animate_stickers": 0, "friend_source_flags": {"all": true}, "guild_folders": [], "custom_status": null}``

Add category ID to message data?

Is it possible to add the category ID in addition to the guild ID and channel ID when a message is received?


arandomnewaccount:
as an improvement to discum? Personally, I feel like this would unnecessarily deviate from the raw, pure data received from discord (in the parsing functions, you can see that I try not to over process the data because ultimately it is the user's choice on how to process the data). Anyway, need not fear, since the category ID can be easily found be looking at the data from your current discord (gateway) session:

bot.gateway.session.guild('GUILD_ID_STR').channel('CHANNEL_ID_STR')['parent_id']

which returns the string category id that the channel belongs to.

Joining guild after using setAvatar function locks account

I tried with 10+ tokens, after I put an avatar with discum.py, I installed it with downloading the zip and then installing it with pip, even If I manually join a guild, instantly I get blocked and discord automatically asks for verification. Also after I set an avatar, I cant seem to send messages to a channel, says that I'm unauthorized. I've tried to get my profile via info() and getProfile(), didnt work. I tried to put some delay, didnt work neither.
note:I'm using freshly generated tokens, they dont have mails and passwords. Maybe it's because I'm just using tokens, but you can change your avatar manually without setting email or password.

It would be nice to change avatars automatically. If you need more info, I'll give you updates.


arandomnewaccount:
weird, I tested the setAvatar function with my account and it worked perfectly. Also, the setAvatar function doesn't need email/password so it shouldn't be a problem that you're using tokens (I use tokens, too).
My best guess is that discord is blocking your accounts for joining guilds; not sure...

Just a little question about "gateway" and "resp"

I'm a beginner and I really want to understand this because it would help me using your library of functions(or whatever it's called) a lot better

Can you thoroughly explain me what exactly represent a "gateway", what happens when I use bot.gateway.run(auto_reconnect=True) I thought we connect through discum.Client(token='your token'), what exactly is 'resp' and how to use it properly. and also what is bot.gateway.command exactly.

In your code example : https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/examples/gettingGuildMembers.py
I'm not following something, it seems that you use the function bot.gateway.fetchMembers before using bot.gateway.run, so is it like you announce all the gateway.functions you want to use and then you use bot.gateway.run to actually send them to discord ?

But then why isbot.gateway.command({'function': **close_after_fetching**, 'params': {'guild_id': guild_id}})before the bot.gateway.run, shouldn't the 'close_after_fetching' be after get_members function finishes ?

I think if I can understand this code I'll understand a lot better how to work with it, so I really hope you can help me with this <3 Thank you !

UNIX Systems

Hi, i really like your library, but i need to run it on a cloud service which runs on Ubuntu
So can you make it compatible with Ubuntu too?

I get error:
File "/app/.heroku/python/lib/python3.7/site-packages/discum/discum.py", line 43, in __init__ self.__user_token = self.__login.GetToken() #update token from "none" to true string value File "/app/.heroku/python/lib/python3.7/site-packages/discum/Login.py", line 39, in GetToken self.Connect() File "/app/.heroku/python/lib/python3.7/site-packages/discum/Login.py", line 35, in Connect self.__token = json.loads(response.content)['token'] KeyError: 'token'

And i think it is because it is running on ubuntu

Edit:
Fixed it by adding a token as well as email and password

account permanently disabled

This package looked great! Unfortunately, I was only able to test it for ~1h before I received an email from Discord saying I was banned.
During these tests I sent 2 test DMS, tried reading messages in different channels etc.
It worked really well. And before you ask, no I didn't spam or did anything weird, I was still in the testing phase.

Please let me know if you're able to circumvent Discord's detection! I only need a bot to read messages and process them privately (in a channel that will not accept bots), nothing else.

How to measure ping from websocket gateway

Hello!

I tried to look from the documentation but didn't find any ways to measure the ping to the websocket gateway, any ideas how to measure the latency between receiving the message from the websocket?

The discord.js library has a function named client.ws.ping which, referring to the docs, prints the number that is your latency to the gateway. Don't know how that is implemented.


arandomnewaccount:
well, according to discord.py (https://github.com/Rapptz/discord.py/blob/master/discord/shard.py#L261), latency = seconds between a HEARTBEAT and a HEARTBEAT_ACK.
HEARTBEAT is something your client sends (https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/discum/gateway/gateway.py#L220) and HEARTBEAT_ACK is what discord responds with (opcode 11).
So...it's currently not implemented in discum but when I get some time I can.

edit: added latency calculations in the last commit push. You can access the gateway latency by doing bot.gateway.latency. Also you'll have to wait ~30 seconds on the first gateway connection since that's about how much time discum waits until sending a heartbeat.
Close code handling was also added; make sure you update your websocket-client installation since they updated their lib to send close codes :).

edit: closing this as answered. You can access gateway latency by doing bot.gateway.latency.

getGuildMembers

Hello πŸ‘―, thanks for this open source code ;D i got an issue :

When i execute bot.getGuildMembers(" a guild id")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/dist-packages/discum-0.2.5-py3.8.egg/discum/discum.py", line 351, in getGuildMembers
    return self.getGuildData(guildID,False)['members']
KeyError: 'members'

Edit: I have a question : how can i have the channel id of a user id? (dm)

getMembers Certificate Error

When running the example get members

Randomly generated user agent: Mozilla/5.0 (Linux; Android 7.0; LGL84VL Build/NRD90U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Mobile Safari/537.36
Retrieving Discord's build number...
Discord is currently on build number 80886
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)
websocket closed
Connection Dropped. Retrying in 10 seconds.

About function joinGuild(self,inviteCode)

Every time when I call this function, due to against Tos, my discord account disabled.
I spent several accounts , finally finding out the disabled reason.
So, is there any way to solve this problem?

PS: All of my test tokens is verified by phone and email. And there is no problem if I using discord app do same operations.


arandomnewaccount: dang they're disabling accounts now from this. Ok, well, for now it might just be better to use a browser automator (like selenium, pyppeteer, etc) and maybe also a stealth plugin to go with that when creating dms, requesting friends, and joining guilds.

Depending on what discord is checking for, the selfbot detection bypass (if we find it) will/won't be coded into discum. If it's not coded into discum, I might write a few examples in https://github.com/Merubokkusu/Discord-S.C.U.M/tree/master/examples.

Anyway, thanks for sacrificing those accounts. Any info on what discord uses to phone lock and/or disable accs is useful.
However, next time an account gets disabled, it might be better to ask (either on here or on r/discord_selfbots) to minimize accs getting "used up".

edit:
closing this.

Correct way of using fetchMembers

Hi, I've been using this example to experiment with fetching discords ranging from 1,000 members to 30,000 members.
https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/examples/gettingGuildMembers.py

However I have noticed after the flag of bot.gateway.finishedMemberFetching(guild_id): is valid it will only return 6,000 - 7,000.
I thought I could solve this issue by increasing the startIndex by 50 each search until it would reach an expected value I manually defined.

ie

bot.gateway.fetchMembers(guild_id, channel_id, keep="all", wait=2, method="no overlap", startIndex=index) #get all user attributes, wait 1 second between requests

and once the fetch is finished index would increase by 50.

However my findings are very unreliable or just not working at all?

Starting Search at 0 seconds with startIndex 0
5780 members fetched
Starting Search 2 at 224 seconds with startIndex 60
82 members fetched
Starting Search 3 at 314 seconds with startIndex 120
81 members fetched
done

My code is almost identical to the example listed above however I added a loop to call the get_members function after completion - this leads to the question, what is the appropriate way to fully fetch a server members?


arandomnewaccount:
it looks like what's happening here is the guild you're experimenting on has 6000-7000 fetchable members (note, # of members your client can see is usually less than the # of total members). To calculate the # of fetchable members, do this: https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/docs/fetchingGuildMembers.md#calculating--of-fetchable-members

As for your looping, any start index will update the first member group (up to 100 members) since the request for lazy requesting is always for the 0,99 range (explains why you're getting 81-82 members fetched) (

self.gatewayobj.request.lazyGuild(guild_id, {channel_id: [[0,99]]}, typing=True, threads=False, activities=True, members=[])
). To check if this is the case, see if the size of the member list is increasing each time you're increasing the start index (test it with bot.gateway.fetchMembers(..., reset=False). If the member list size doesn't increase, then the already-fetched members are just getting updated.

Anyways, I can do some tests later today to double check that it's working smoothly.

edit:
just double checked on my end on a few guilds (both small and large) and it's working smoothly.

edit:
Closing this issue in 2 days if there's no response.
tldr of what I said above:
The examples for fetching members given in this repo are correct. No, you should not be using a loop with increasing start indexes (start index is only actually useful if discord closes your connection to the gateway while you're still fetching the member list).

Fetch all members of a guild

Currently, I could not get a workaround to get all members for a discord because of the new intent feature addition. Is you API support to fetch all members of a guild?


hey it's arandomnewaccount responding by editing your comment (my account is hidden).
Anyways, user accounts don't use intents to connect to the gateway (that's only for bots). That being said, discum is only supported for user accounts. In the examples, we have 2 codes that will fetch guild members:
this for getting members in small guilds {<100k members}
and this for getting guild members in guilds {of any size}

These have been tested on guilds of various sizes (many of which were over 100k members).
Soon (in the next version), a fetchMembers function will be built into the api wrapper. If you want a quick solution, use the examples above.

Issue in notOfflineCachedMemberIDs

So i have been trying to use notOfflineCachedMemberIDs attribute, to get the ids of the online members only (not sure if thats what it suppose to do). However, if it is then it gives me an error message merged_members key not found. Could you please look into this? I really need to use this, or tell me an alternative to get the online users ids only for a guild.

File "/usr/local/lib/python3.8/dist-packages/discum-1.0.0-py3.8.egg/discum/gateway/session.py", line 402, in notOfflineCachedMembers
return session.settings_ready_supp['merged_members'][self.guildIndex]
KeyError: 'merged_members'


hey it's arandomnewaccount replying by editing (my accs hidden):
Since you're getting a key error, one of 2 things is happening: either you havent connected to the gateway yet or you ran this command after resp.event.ready.
Either way, merged_members is essentially useless (it'll prob give you 10 users, at best).
Instead, use discum's fetchMembers function: https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/docs/fetchingGuildMembers.md
I can add some code to fetchMembers in a bit to have it stop fetching after getting online/offline members.

Running the init command gives a syntax error

When I run the command from the CLI

discum.Client(email="[email protected]", password="Test1234!", token="Token.token.Token", proxy_host=False, proxy_port=False, user_agent="random", log=True)

I get an error:

-bash: syntax error near unexpected token `email="[email protected]",'

I followed the installation steps as stated.

It's a debian10 64-bit clean install machine


hey it's arandomnewaccount replying by editing again :/.
Anyways the reason you're getting errors is because proxy_host and proxy_port normally default to None (not False).
I just realized you ran that command in bash. Um so yea don't do that. Run it in the python interpreter or make a bot.py file and run that with python.

multibots

any ideas how to run multiple bots at the same time?

websocket closed

Receiving websocket closed on a fairly simple programme. Read a previous issue regarding this which you acknowledged and said may be fixed by now but I'm not having any luck. Do you have any modifications I could make to code to get around this error such as restarting the websocket connection after it is closed? Thanks

Is their not any function to join a server via invite?

Looking for a system to join a discord server. It seems strange that as in depth featured as this is their is no method to do this (unless I missed it).

Is this a likely feature to be added in the near future? CURL commands have failed me.

Messages on API V9

Does this still work to get messages after discord removed their route ?


arandomnewaccount:
Both the http route (bot.getMessages) and the gateway should still work. In fact, I tested it on gateway messages with the fresh account and I'm getting both embed and content data.

commands & events

Hello,
If i create some commands using @bot.gateway.command
The bot response to all messages.
Is there a way to create commands and define a prefix into a variable that will be need to be used in order to use commands?


arandomnewaccount:
yep. The only thing needed to implement a prefix is to check the beginning of a message string. So, a simple example would be:

@bot.gateway.command
def test(resp):
	if resp.event.message:
		m = resp.parsed.auto()
		if m['content'].startswith('!'):
			cmd = m['content'][1:]
			if cmd == "reply":
				bot.reply(m['channel_id'], m['id'], 'hi')

What the code above does is it checks if every message starts with the prefix ! and if it does, checks if the command is "reply". If it is, it replies to the message with "hi".

If we want to pass in the prefix as a parameter, we can do that too:

def test(resp, prefix):
	if resp.event.message:
		m = resp.parsed.auto()
		if m['content'].startswith(prefix):
			cmd = m['content'][1:]
			if cmd == "reply":
				bot.reply(m['channel_id'], m['id'], 'hi')

prefix = "!"
bot.gateway.command({"function": test, "params": {"prefix": prefix}})

Similarly, we can also pass in the command/function as a parameter:

def prefixHandler(resp, prefix, function):
	if resp.event.message:
		m = resp.parsed.auto()
		if m['content'].startswith(prefix):
			cmd = m['content'][1:]
			function(cmd, m)

def reply(cmd, m):
	if cmd == "reply":
		bot.reply(m['channel_id'], m['id'], 'hi')

prefix = "!"
bot.gateway.command({"function": prefixHandler, "params": {"prefix": prefix, "function": reply}})

gateway.session.guildIDs() does not work

print(discumbot.gateway.session.guildIDs())
discumbot.gateway.run()
discumbot.gateway.resetSession()

it gives the error:

Traceback (most recent call last):
  File "C:/Users/CUPZYY/Documents/Python Projects/Discord-Tag-Change-Bot/main.py", line 108, in <module>
    startFetch()
  File "C:/Users/CUPZYY/Documents/Python Projects/Discord-Tag-Change-Bot/main.py", line 103, in startFetch
    print(discumbot.gateway.session.guildIDs())
  File "C:\Users\CUPZYY\AppData\Local\Programs\Python\Python37\lib\site-packages\discum\gateway\session.py", line 36, in guildIDs
    return [guildID for guildID in self.guilds if "removed" not in self.guilds[guildID]]
  File "C:\Users\CUPZYY\AppData\Local\Programs\Python\Python37\lib\site-packages\discum\gateway\session.py", line 28, in guilds
    return self.settings_ready['guilds']
KeyError: 'guilds'

arandomnewaccount:
you have to connect to the gateway first in order to receive any gateway session data
so, like this:

discumbot.gateway.run() #connect to the gateway, after a few seconds you can do ctrl-c
print(discumbot.gateway.session.guildIDs) #guildIDs is not callable so no ()

Status not showing up

Hi! I'm trying to make a self-bot that sets a custom status and then stays online forever. I tried this:

import discum

bot = discum.Client(token="token")
bot.setStatus("my custom status")
bot.gateway.run(auto_reconnect=True)

The bot stays online, but the status doesn't show up when I check from another account. What am I doing wrong?
Cheers!


arandomnewaccount:
oh I think see what's happening.
What I think is going on here is the IDENTIFY message your client is sending out (when running bot.gateway.run() says to discord that your status is online (https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/discum/gateway/gateway.py#L64), which is then changing your status. I'm going to have to do a few more tests to confirm, and if that's indeed the case, then I'll be fixing it in an upcoming commit.

If that's the case, then the custom status should show if you don't connect to the gateway...

edit: just tested it and the gateway connection does not affect the status so...
My other guess is that your other account is not getting updates for your current account's presence changes. See if the profile of your current account (viewed from your other account) shows the custom status (right-click on username -> click profile). If it does, then everything is working fine.

2nd edit:
I see now. Tried looking from my other account and couldn't see any evidence of status-changing on my main so...I've got 1 last idea and if that doesn't work idk (I'll have to try tmr since tonight I don't have much time). Thanks for bringing this issue up.

Discussion: Recommended way of using createDMs?

Just wanted to ask if there are any recommended best practices for using createDM as you mention it is one of the calls to be careful with.

Any recommendations on how frequently it's ok to call? Every other second? Every 10 seconds? Is it better to call with many user ids at once or separately for each? If nobody knows, that's ok, I realize some of it is up to personal taste for risk, but wanted to check. Thanks!


arandomnewaccount:
Btw, I'm going to wait until I run a few more tests with the createDM endpoint (& organize some code in RESTapiwrap.py) until I give my recommendations on this. If anyone else has some more experience with creating DMs, feel free to jump in.

Leaving guild?

I can't seem to find anyway to leave a guild in the docs. If it isn't already a thing, could it please be added?


arandomnewaccount: yep I know, it'll be added in the next commit.
edit: added. just do bot.leaveGuild(guildID)
guildID is a string btw.
I'll update the docs later.
edit: updated the docs

GetMembers EVEN for Offline?

def close_after_fetching(resp, guild_id):
    if bot.gateway.finishedMemberFetching(guild_id):
        lenmembersfetched = len(bot.gateway.session.guild(
            guild_id).members)  # this line is optional
        # this line is optional
        print(str(lenmembersfetched)+' members fetched')
        bot.gateway.removeCommand(
            {'function': close_after_fetching, 'params': {'guild_id': guild_id}})
        bot.gateway.close()


def get_members(guild_id, channel_id):
    # get all user attributes, wait 1 second between requests
    bot.gateway.fetchMembers(guild_id, channel_id, keep="all", wait=1)
    bot.gateway.command({'function': close_after_fetching,
                         'params': {'guild_id': guild_id}})
    bot.gateway.run()
    bot.gateway.resetSession()  # saves 10 seconds when gateway is run again
    return bot.gateway.session.guild(guild_id).members
^ Does the library not catch OFFLINE members? It should no? Is this an issue for guilds that DO NOT display offline members?

arandomnewaccount:
As noted in the docs for this fetchMembers function (https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/docs/fetchingGuildMembers.md), large guilds do not have offline members in their member list sidebar. Since the fetchMembers function only looks at that sidebar, well, you get what your client can see.
See issue #40 for more info on this.

You can, however, get some offline members from a guild using opcode 8 and some "guesses":

bot.gateway.request.searchGuildMembers([guild_id], query, limit=100) #from my tests, even if you put a larger limit you still only get 100 results back

where query is some string that you want to search guild members with. Unfortunately, unless you have manage server permissions, you cannot use an empty query ("").

The responses will be of type GUILD_MEMBER_CHUNK. There's a parser in discum for this event:

resp.parsed.guild_members_chunk()

Note that you will get both online and offline members in the responses.

When I get some more time I'll probably post an example on this op 8 "brute forcing".

edit:
added an opcode 8 brute forcer in the examples: https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/examples/searchGuildMembers.py#L108

I still want to test it out some more, but once things are looking a bit more final I'll put the gateway searchGuildMembers function into discum. However, I'll be keeping the brute forcer as an example (not putting it into discum) since the client does not normally brute force opcode 8 events to get the member list.

I've optimized the brute forcer as much as I can rn (minimize the # of useless opcode 8s and maximize the # of members updated per guild_members_chunk). For some reason, for many guilds it doesn't return all the members. I assume I messed up somewhere in the brute forcer, but it could also be that discord isn't sending all results back. Feel free take a stab at improving the brute forcer.

edit: closing this since theres a op8 brute forcer in the examples.

test

test issue


test

Cant fetch member objects

So you can fetch a member object from the on message event, proven in the example below

@bot.gateway.command
def helloworld(resp):
    if resp.event.ready_supplemental: #ready_supplemental is sent after ready
        user = bot.gateway.session.user
        print("Logged in as {}#{}".format(user['username'], user['discriminator']))
    if resp.event.message:
        m = resp.parsed.auto()
        guildID = m['guild_id'] if 'guild_id' in m else None #because DMs are technically channels too
        channelID = m['channel_id']
        username = m['author']['username']
        discriminator = m['author']['discriminator']
        content = m['content']
        print("> guild {} channel {} | {}#{}: {}".format(guildID, channelID, username, discriminator, content))

But if I want to fetch members in general , I can only get ID's? How can I get the member object like the code above?! is this missing in this library?

suggestion?

Maybe make a github page for the docs or something, since that would be easier to read and yeah

Fetch members example does not work: Error 'GatewayServer' object has no attribute 'fetchMembers'

Exception has occurred: AttributeError
'GatewayServer' object has no attribute 'fetchMembers'
  File "/home/username/Documents/discord count/UserDB/test.py", line 21, in get_members
    bot.gateway.fetchMembers(guild_id, channel_id)
  File "/home/username/Documents/discord count/UserDB/test.py", line 26, in <module>
    members = get_members('validid', 'validid')

Steps to re-produce: Run the example with a user token and valid guild and channel IDs


Hey it's arandomnewaccount replying by editing (bc my acc is hidden):
Did you install discum through pip or through github? Most likely, you're getting attribute errors because you installed through pip (which is currently outdated, and does not have a fetchMembers attribute in GatewayServer). Try to instead reinstall through github:

git clone https://github.com/Merubokkusu/Discord-S.C.U.M.git
cd Discord-S.C.U.M
python setup.py install

I get an error with create a DM

ok so I used the example to fetsh members wich is working correctly. I get all their ids and using for loop I want to create a DM channel foreach of them.

`@bot.gateway.command
def memberTest(resp):
guild_id = '714338144954351669'
channel_id = '743719231274876998'
if resp.event.ready_supplemental:
bot.gateway.fetchMembers(guild_id, channel_id)
if bot.gateway.finishedMemberFetching(guild_id):
bot.gateway.removeCommand(memberTest)
bot.gateway.close()

bot.gateway.run()
print('aa')
for member in bot.gateway.session.guild('714338144954351669').members:
bot.createDM([member])`

When I replace member with a manual id its working fine.

arandomnewaccount:
disclaimer: a mass dm is a bad idea since it can get your account flagged pretty quickly.
Anyway, with that in mind, I tried the code that you sent and it worked on my end. You might get some response 400s due to ppl turning off their direct-messages & you can't dm yourself, but that's it.
Also, I just got my alt account "flagged" (I'll need to use a phone number to verify) and I only did 3 createDM calls (with no wait time) so...yea...I don't recommend it.

This is the code I used btw:

for member in bot.gateway.session.guild("guild id here").members:
    if member != "my user id here": #this check isnt necessary, but it saves you one createDM call
        bot.createDM([member])

Suggestion:Adding multi bot example to example folder

Basically, it would probably really help people just learning how to use discum if there was an example of how to implement the multi token concepts referenced in issue #22 and #36. I personally could not use the code provided in issue #22 and had to work around it.

Thanks,
Callihan


edit here

Awaiting for messages?

Hi! I am currently creating a bot that drops and grabs cards from Karuta BOT. I have already managed to make it quite independent but in somewhat obscure way, it relies 100% on events. The thing that would help me a lot would be some way to wait for these messages, here's example:

BOT sends command k!c, awaits for message from <@646937666251915264> on public channel, gathers message and adds reaction to it

bot.sendMessage(channel_ID, "k!c") response = await bot.gateway.command if response['content'] == "x": msg_ID = response['id'] bot.addReaction(channel_ID, msg_ID, "βœ…")

Is it possible? If so, could you give me a brief example/explaination on a way I can implement this? Thanks :)

'websocket closed' after about 3-4 hours

Hello,

After a few hours discum stops with websocket closed, nothing in the logs to say why.

Don't really understand why because auto_reconnect=True is a while loop right?

Below is an example of the code im running.

BTW, thanks for creating this, very nice work.

class DiscordBot(Process):
    def __init__(self, config):
        self.__config = config
        super().__init__()

    def bot_wrapper(self, config):
        LOG.info("DiscordBot started")
        bot = discum.Client(token=config.token, locale="en-UK", log=True)
        @bot.gateway.command
        def discord_callback(resp):
            if resp.__dict__['raw']['t'] is not None:  # Skip heartbeat
                ts = datetime.now().strftime("%Y%m%d-%H%M%S%f")
                fn = "pickles/{}_{}.pickle".format(ts, resp.__dict__['raw']['t'])
                with open(fn, 'wb') as f:
                    pickle.dump(resp, f)
        bot.gateway.run(auto_reconnect=True)
        LOG.info("DiscordBot stopped")

    def run(self):
        self.bot_wrapper(self.__config)

arandomnewaccount:
yep I'd also encountered this - every ~3 hours discord closes the gateway connection. The latest version (on github) shouldn't run into this problem since it uses a recursive call. So, let me know if updating your version fixes it.
The latest version however fails to stop reconnecting after keyboard interrupts or ws.close() calls by the developer so currently editing another version that'll fix that...

edit: just pushed the update. Tested it on my accounts today and it's been working smoothly for me (you'll have to reinstall to the latest version on this repo). Let me know how it goes on your end.

i get this error message when i run the code (bot.gateway.fetchMembers)

I am a kind of a beginner to all of this so don't blame me for a small mistake

`import discum
import time
#bot = discum.Client(email=,password=) #note, this will not work if you have a MFA account
#bot = discum.Client(email=,password=,proxy_host=,proxy_port=,user_agent=)
#bot = discum.Client(email=,password=,token=) #works for all types of accounts
bot = discum.Client(token="") #works for all types of accounts, no profile editing however
#bot = discum.Client(token=,proxy_host=,proxy_port=) #works for all types of accounts, no profile editing however
@bot.gateway.command
def myf(resp):
guild_id = "765186126684094474"
channel_id = '767056897106640927'
bot.gateway.fetchMembers(guild_id, channel_id)
bot.gateway.run(auto_reconnect=True)

`

i see nothing wrong with it after i read the wiki, but what i get is:

Exception ignored in thread started by: <bound method GatewayServer._response_loop of <discum.gateway.gateway.GatewayServer object at 0x000001B303F263D0>>
Traceback (most recent call last):
File "c:\users\user\pycharmprojects\pythonprojectnew\venv\src\discum\discum\gateway\gateway.py", line 232, in _response_loop
func(resp)
File "C:/Users/user/PycharmProjects/pythonProjectNEW/main.py", line 12, in myf
bot.gateway.fetchMembers(guild_id, channel_id)
File "c:\users\user\pycharmprojects\pythonprojectnew\venv\src\discum\discum\gateway\gateway.py", line 296, in fetchMembers
"function": Guild(self).fetchMembers,
NameError: name 'Guild' is not defined


arandomnewaccount (can only edit cause my acc's hidden):
hey thanks for bringing this to my attention. I'd forgotten to change Guild to GuildCombo. It should be working now. I'll test it on my end just to make sure.

Command setup?

Sorry I am very new to this type of stuff, but I want to know how to get user input from discord in order to interact with the bot, like for example

If I use command ".help" in discord chat and then it shows up an embedded list of other commands how would I do that?


arandomnewaccount:
well essentially you have to listen to messages and if the message is .help then the help embed is sent
so like this:

@bot.gateway.command
def helpembed(resp):
    if resp.event.message:
        m=resp.parsed.auto()
        if m['content'] == '.help':
            bot.sendMessage(m['channel_id'], embed=embedstuff)

Here're the docs on creating embeds: https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/docs/using.md#send-embed

Now, for command prefixes you can set an instance variable (like bot.prefix, or any other name), and just do some string checking (like if m['content'].startswith(bot.prefix): ...)

edit: lemme know if that helps

No response so I'm closing this for now. Feel free to open another issue if you have other questions about this.

afterDate and beginDate query params should be switched

Currently beforeDate is associated with the query "min_id." However, I did a quick test and checked that the param should be "max_id"

Search
HTTP

################################
Hey it’s arandomnewaccount responding by editing your message.
Thanks for pointing this out - accepted your pull request! :)

How to disable logging?

How would I disable the Logging? Don't really want to have to override the logger function.


aight so here I am arandomnewaccount editing your message as an answer because github won't let me post public comments...hope this works lol. I added the ability to disable the logging when you initiate the bot:

bot = discum.Client(email="",password="",log=False)

also, at any time in the code, you can set the bot.log boolean to toggle logging on/off:

bot.log=True
bot.log=False

also, I'll note that since the bot._Client__gateway_server.runIt function is still kinda experimental, you'll need to specify for that function whether you want logging or not:

# so, for example, when running bot._Client__gateway_server.runIt:
bot._Client__gateway_server.runIt({
  1: {
    "send": [],
    "receive": []
  }
}, log=True)

fetchMembers doesn't include offline members

Hi, I ran a version of this:

https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/examples/gettingGuildMembers.py

and tacked on:

members_list = list(members.values())
count = collections.Counter([m['presence']['status'] for m in members_list])
print(count)

which returns (note: I have replaced numbers with ----):

Counter({'online': ----, 'idle': ----, 'dnd': ----})

In other words, no offline members are returned in the list. I know you mentioned that the fetchable members is less than total members, but I didn't see any explicit mention about offline members. Is this expected behavior/is there any way to retrieve offline members? Thanks!


arandomnewaccount:
yea I forgot to include that in the docs thx for bringing it up.
For large guilds (bot.gateway.session.guild('GUILD_ID').large == True), the member list only contains the not-offline members.
Note that some guilds are unavailable before you send the op 14 (bot.gateway.session.guild('GUILD_ID').unavailable == True). Those are massive guilds.

There is a way to get offline members: op 8 (aka search guild members) can. You just need some search queries (a blank string query doesn't work unless you have perms). The more search queries you use, the more members you fetch (pretty sure it's max 100 members per search query). Gonna probs play around with it later this week and hopefully add a searchGuildMembers gateway function soon.

Is there a way to fetch all emojis from a discord server ?

Hey,

I've cheched the list of functions and the closest one I found that may be what I'm looking for is bot.gateway.session.guild(GuildID).emojis

So my code looks like this

import discum
bot = discum.Client(email="", password="", secret="", code="", token="", proxy_host=None, proxy_port=None, user_agent="random", log=True)

test = bot.gateway.session.guild(805547850976591875).emojis
print(test)
@bot.gateway.command
def helloworld(resp):
    if resp.event.ready_supplemental: #ready_supplemental is sent after ready
        user = bot.gateway.session.user
        print("Logged in as {}#{}".format(user['username'], user['discriminator']))
    if resp.event.message:
        m = resp.parsed.auto()
        guildID = m['guild_id'] if 'guild_id' in m else None #because DMs are technically channels too
        channelID = m['channel_id']
        username = m['author']['username']
        discriminator = m['author']['discriminator']
        content = m['content']
        print("> guild {} channel {} | {}#{}: {}".format(guildID, channelID, username, discriminator, content))

bot.gateway.run(auto_reconnect=True)

But it returns

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    test = bot.gateway.session.guild(*guildID here*).emojis
AttributeError: 'GatewayServer' object has no attribute 'session'

I'm not sure what's up :/ Also, I've seen someone got banned from using this script, do you have recommendations on what precautions I should take while using this tool to minimize the risks ? Thanks !

wonder how to dm someone with a mutual server

arandomnewaccount:
As stated in the readme, bot.createDM, bot.requestFriend, and bot.joinGuild are risky to use. I highly recommend using a browser automator (like selenium or pyppeteer) for these 3 actions.

edit: closing this as it's pretty much a duplicate of #41

Exception in thread started by GatewayServer._response_loop

Hello! I've been playing around with this library, specifically running this example, the only difference being that I clear the command after printing the user instead of when I receive a message, but from time to time I randomly get the following error after starting the example:

Exception ignored in thread started by: <bound method GatewayServer._response_loop of <discum.gateway.gateway.GatewayServer object at 0x7fc82cc17d90>>
Traceback (most recent call last):
  File "/home/gilgames/Documents/bot/venv/lib/python3.9/site-packages/discum/gateway/gateway.py", line 233, in _response_loop
    if self._after_message_hooks[index] == None: #if function removed
IndexError: list index out of range

I can't find out why this happens, any idea? Is it possible that there is some kind of race condition going on?


arandomnewaccount:
hey sry this is due to the while loop implemented in a few commits back not working too well for the response loop. Looks like you found one of the times where it breaks. Anyways, the most up to date version (1.1.0) uses a for loop instead that makes a copy of the commands list and therefore doesn't break (so just update your discum installation).
I was thinking of using a linked list but that has problems of its own with efficiency (plus my linked list test code for discum is kinda messy rn lol) so I've settled on a for loop for now.

Getting an opcode 7 even when your code says it won't happen

Hello, I began using discum recently and I have a gateway running 24/7 (at least it should be running 24/7), but occasionally it gets opcode 7's for which I decided to abandon the connection and just start a new one. This is how I handled an opcode 7. This solution is very scuffed and every 24-30 hours, Ill get an opcode 9 and the entire thing will just stop working. Do you guys have a cleaner way of handling / resuming connections?

def start_reader():
    @bot.gateway.command
    def message_reader(resp):
        if resp.raw["op"] == 7:
            globs.logging(None, 6, f"op code 7 received by discord > {resp.raw}... Restarting Connection") # my own logging
            bot.gateway.close()
            thread_handler.kill_thread(g.gateway_thread)
            bot.gateway._after_message_hooks = []
            bot = discum.Client(token=g.tokens["1"], log=False)
            start_reader()
            g.gateway_thread = threading.Thread(target=bot.gateway.run, name='gateway', kwargs={"auto_reconnect": True})
            g.gateway_thread.start()
            return
        # actual message parsing goes here

arandomnewaccount:
huh, I dont remember seeing op7 nor op9 gateway responses in my tests. Something must've changed in the api cause last time I tested the code and was able to run it for a few days. Anyway I'll run a few tests and get back to you after a few days.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.