Skip to content

Commit

Permalink
first initial
Browse files Browse the repository at this point in the history
  • Loading branch information
ilkergzlkkr committed Apr 1, 2021
0 parents commit db5ff42
Show file tree
Hide file tree
Showing 13 changed files with 675 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DCLIST_TOKEN=
50 changes: 50 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# pyenv
.python-version
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

### VisualStudioCode ###
.vscode/*
.vscode/
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace

### CURRENT PROJECT ###
temp/
*.log
*.log.*
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 ilkergzlkkr

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include README.md
include LICENSE
87 changes: 87 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# DCList.net Python SDK

This module is official python sdk for dclist.net.

It's open-source and always open to prs and contributions.

## Installation

You can install package via [pip](https://www.pypi.org/dclist.py) or [github](https://github.com/dclist/python-sdk) with following commands :

**Recomended**:
```
pip install dclist.py
```

or

```sh
git clone https://github.com/dclist/python-sdk.git
cd python-sdk
python -m venv env
pip install .
```

## Gettings Started

### Posting botstats automaticly as a Cog:
```py
import dclist

from discord.ext import commands, tasks

class dclistpy(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.dclistapi = dclist.DCLClient(bot, "YOUR_TOKEN_HERE")
# you can get the token from your bot's page on dclist.net
# you have option to pass your token as environment variable as `DCLIST_TOKEN`
self.update_stats.start()

def cog_unload(self):
self.update_stats.cancel()

@tasks.loop(minutes=30.0)
async def update_stats(self):
await self.bot.wait_until_ready()
try:
await self.dclistapi.postBotStats()
except dclist.DCListException as e:
print(e)
# print sucs lol use logger instead :walter_the_dog:
else:
print('Posted stats to dclist.net successfully')

def setup(bot):
bot.add_cog(dclistpy(bot))
```

### Getting bot or user info from api:
```py
@commands.group(invoke_without_command=True)
async def dclist(self, ctx):
await ctx.send('available commands -> `dclist bot` `dclist user` `dclist voted`')

@dclist.command(name="bot")
async def get_dclist_bot(self, ctx, bot_id):
bot = await self.dclistapi.getBotById(bot_id)
to_send = f"found bot {bot['username']} using this github {bot['github']} and vote_count is {bot['stats']['voteCount']}"
await ctx.send(to_send)

@dclist.command(name="user")
async def get_dclist_user(self, ctx, user_id):
user = await self.dclistapi.getUserById(user_id)
to_send = f"found user {user['username']} using this website {user['website']} and discriminator is {user['discriminator']}"
await ctx.send(to_send)

@dclist.command(name="voted")
async def get_dclist_user(self, ctx, user_id):
is_voted = await self.dclistapi.isUserVoted(user_id)
if is_voted:
await ctx.send('yessir, i did voted from this dude.')
else:
await ctx.send('this user is not voted :(')
```
## More

You can use sdk to get more information like `getUserComment`.
26 changes: 26 additions & 0 deletions dclist/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
GQL-API wrapper
~~~~~~~~~~~~~~~~~~~
A gql wrapper for the dclist.net API.
:copyright: (c) 2021-present ilkergzlkkr
:license: MIT, see LICENSE for more details.
"""

__title__ = 'dclist.py'
__author__ = 'ilkergzlkkr'
__copyright__ = 'Copyright 2021-present ilkergzlkkr'
__license__ = 'MIT'
__version__ = '0.1.0'

from collections import namedtuple
VersionInfo = namedtuple('VersionInfo', 'major minor micro releaselevel serial')
version_info = VersionInfo(major=0, minor=1, micro=0, releaselevel='final', serial=0)

version_info = f'{version_info.major}.{version_info.minor}.{version_info.micro}'

from .client import DCLClient
from .gqlhttp import GQLHTTPClient
from .errors import *
154 changes: 154 additions & 0 deletions dclist/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
"""
MIT License
Copyright (c) 2021 ilkergzlkkr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import logging, os
import typing as t

from . import errors
from .gqlhttp import GQLHTTPClient

log = logging.getLogger(__name__)

class DCLClient:
"""
API wrapper for dclist.net
--------------------------
Parameters
----------
bot: discord.Client
An instance of a discord.py Client object.
token: str
Your bot's Dclist.Net API Token.
**loop: Optional[event loop]
An `event loop` to use for asynchronous operations.
Defaults to ``bot.loop``.
**transporter: Optional[gql.transport]
A `gql.transport` to use for transporting graphql queries.
"""

def __init__(self, bot, api_token: t.Optional[str]=None, *args, **kwargs):
if api_token is None:
log.warning("No Token Provided. DCLClient never gonna post bot stats.")
self.bot = bot
self.bot_id = None
self.loop = kwargs.get("loop", bot.loop)
self.http = GQLHTTPClient(api_token, loop=self.loop, transporter=kwargs.get('transporter'))

async def __get_ready(self):
await self.bot.wait_until_ready()
if self.bot_id is None:
self.bot_id = self.bot.user.id

async def _get_app_info(self):
await self.__get_ready()
return self.bot_id, (await self.bot.application_info()).owner.id


async def postBotStats(self, guild_count: t.Optional[int]=None,
user_count: t.Optional[int]=None, shard_count: t.Optional[int]=None):
"""
Post bot stats to the API
Parameters
----------
:param guild_count: Guild count (optional)
:param user_count: User count (optional)
:param shard_count: User count (optional)
"""
await self.__get_ready()
if guild_count is None:
guild_count = len(self.bot.guilds)
if user_count is None:
guild_count = len(list(self.bot.get_all_members()))
data = await self.http.postBotStats(guild_count, user_count, shard_count)
return data['postBotStats']

async def getBotById(self, bot_id: t.Optional[int]) -> dict:
"""
Get a bot listed on dclist.net
Parameters
----------
:param bot_id: Bot id to be fetched
if bot_id is not given. self bot will be used for getting stats.
Returns
-------
bot: Bot as a dict fetched from gql-api
"""
if bot_id is None:
bot_id, _ = await _get_app_info()

data = await self.http.getBotById(bot_id)
return data['getBot']

async def getUserById(self, user_id: t.Optional[int]) -> dict:
"""
Get a user from dclist.net.
Parameters
----------
:param user_id: User id to be fetched.
if user_id is not given. self bot owner will be used for getting stats.
Returns
-------
user: User as a dict fetched from gql-api.
"""
if user_id is None:
_, user_id = await _get_app_info()

data = await self.http.getUserById(user_id)
return data['getUser']

async def isUserVoted(self, user_id: t.Optional[int]) -> bool:
"""
Is user voted for my bot from dclist.net.
Parameters
----------
:param user_id: User id to be checked.
if user_id is not given. self bot owner will be used for getting voted info.
Returns
-------
:return bool: True or False is user voted.
"""
if user_id is None:
_, user_id = await _get_app_info()

data = await self.http.isUserVoted(user_id)
return data['isUserVoted']

async def getUserComment(self, user_id: t.Optional[int]) -> dict:
"""
Get a user comment from dclist.net from your bot page.
Parameters
----------
:param user_id: User id to be checked.
if user_id is not given. self bot owner will be used for getting comment info.
Returns
-------
:return Comment: Comment stats as a dict fetched from gql-api.
given user must be commented to your any bots. if not so. return value will be None.
"""
if user_id is None:
_, user_id = await _get_app_info()

data = await self.http.getUserComment(user_id)
return data['getUserComment']
Loading

0 comments on commit db5ff42

Please sign in to comment.