Skip to content

Commit

Permalink
Updated to PySDBots v3.0
Browse files Browse the repository at this point in the history
- included major updates
- added an update checker
- Improved code
- fixed bugs

Co-Authored-By: Damantha Jasinghe <damanthaja@gmail.com>
  • Loading branch information
Damantha126 and Damantha126 authored May 11, 2024
1 parent 2299e8e commit 494684b
Show file tree
Hide file tree
Showing 4 changed files with 267 additions and 52 deletions.
4 changes: 1 addition & 3 deletions pysdbots/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from .pysdbots import *

__version__ = "2.1"


__docs__ = req["DOCS"]
__all__ = [
"anime_logo",
"tiktok",
Expand Down
1 change: 1 addition & 0 deletions pysdbots/__version__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = "3.0"
292 changes: 246 additions & 46 deletions pysdbots/pysdbots.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,264 @@
#Copyright © 2024 Damantha Jasinghe
#For the repository at https://github.com/Damantha126/PySDbots

import sys
import requests
from datetime import date
from .__version__ import __version__

# HTTP request headers
headers = {
'Content-Type': 'application/json',
'User-Agent': 'pysdbots'
}

# URL for fetching configurations
CONFIGS="https://gist.githubusercontent.com/Damantha126/b18e14d0d04f25327773e0ab54cc090a/raw/config.json"
# Fetch configurations from the URL
req = requests.get(CONFIGS).json()

# Main class for interacting with SD API
class SDAPI:
notice_displayed = False
"""Main class for interacting with SD API."""
def __init__(self) -> None:
# Initialize notice_displayed flag
self.notice_displayed = False
# Base URL and version information
self.BASE = req["BASE_URL"]
self.VERSION = __version__
self.client = requests
self.api_error = "Failed to retrieve data from the SD API. Please ensure that the API is operational and that your request parameters are correct. If the issue persists, contact support for assistance."


# Display notice only once
if not self.notice_displayed:
self._start()

def _start(self):
"""Display version information and update notice.
Prints information about the current version of PySDBots and displays a notification if a newer version is available.
This method checks the latest available version of PySDBots by querying a remote configuration source.
"""
# Set notice_displayed flag to True
self.notice_displayed = True
year = date.today().year
# Print version information
print(
f'PySDBots v{__version__}, Copyright (C) '
f'2022-{year} Damantha Jasinghe <https://github.com/Damantha126>\n'
'Licensed under the terms of the MIT License, '
'Massachusetts Institute of Technology (MIT)\n',
)
# Check for newer version and print update notice
if req["LAST_VERSION"] != __version__:
text = f'Update Available!\n' \
f'New PySDBots v{req["LAST_VERSION"]} ' \
f'is now available!\n'
if not sys.platform.startswith('win'):
print(f'\033[93m{text}\033[0m')
else:
print(text)

def version(self):
return(self.VERSION)

def _fetch_data(self, method, url, data=None):
"""
Make a request with the specified method.
Args:
method (str): The HTTP method ('GET' or 'POST').
url (str): The URL to send the request to.
data (dict, optional): The JSON data to send in the request body (for 'POST' requests).
Returns:
dict: The JSON response from the API.
Raises:
requests.exceptions.RequestException: If the request encounters an error (e.g., network issues, server errors).
"""
try:
if method == "GET":
# Send a GET request with the specified URL and headers
response = self.client.get(url)
elif method == "POST":
# Send a POST request with the specified URL, headers, and JSON data
response = self.client.post(url=url, headers=headers, json=data)

# Check for errors in the response (e.g., 4xx or 5xx status codes)
response.raise_for_status()
# Parse the JSON response and return it
return response.json()

except requests.exceptions.RequestException as e:
# Re-raise the request exception if an error occurs
print(f"Error occurred: {e}\n", self.api_error)
return None

def anime_logo(self, name):
"""Generate images with anime characters.
Args:
name (str): The name to include in the generated image.
Returns:
str: URL of the generated image hosted on telegra.ph.
This method generates an image with anime characters based on the provided name and returns the URL of the generated image hosted on telegra.ph.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/anime-logo?name={name}")
except:
raise Exception(self.api_error)

def tiktok(self, url):
"""Get TikTok video information from a URL.
Args:
url (str): The URL of the TikTok video.
Returns:
dict: JSON object containing information about the TikTok video.
This method retrieves information about a TikTok video from the provided URL and returns it as a JSON object.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/tiktok?url={url}")
except:
raise Exception(self.api_error)

def apod(self):
"""Retrieve Astronomy Picture of the Day (APOD) from NASA.
Returns:
dict: JSON object with information about the APOD, including date, explanation, image URL, and title.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/apod")
except:
raise Exception(self.api_error)

def detect_lang(self, text):
"""Detect the language of a given text.
Args:
text (str): The text to analyze for language detection.
Returns:
dict: JSON object with the detected language.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/detect?text={text}")
except:
raise Exception(self.api_error)

def write(self, text):
"""Generate a note from the provided text.
Args:
text (str): The text content of the note.
Returns:
str: URL of the generated note.
"""
try:
body = {"text": f"{text}"}
return self._fetch_data("POST", f"{self.BASE}/write", data=body)
except:
raise Exception(self.api_error)

def chk(self, cc):
"""Check information related to a given credit card.
Args:
cc (str): The credit card to check.
Returns:
dict: JSON object with information related to the credit card.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/chk?cc={cc}")
except:
raise Exception(self.api_error)

headers={'Content-Type': 'application/json'}
def sk_checker(self, key):
"""Check information related to a Stripe API Keys.
Args:
key (str): The sk key to check.
def anime_logo(name):
API = f"https://api.sdbots.tech/anime-logo?name={name}"
req = requests.get(API).url
return(req)
Returns:
dict: JSON object with information related to the Stripe API Keys.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/sk?key={key}")
except:
raise Exception(self.api_error)

def tiktok(url):
API = f"https://api.sdbots.tech/tiktok?url={url}"
req = requests.get(API).json()
return(req)
def lyrics(self, song):
"""Retrieve lyrics for a given song.
def apod():
API = "https://api.sdbots.tech/apod"
req = requests.get(API).json()
return(req)
Args:
song (str): The name of the song.
def detect_lang(text):
req = requests.get(f"https://api.sdbots.tech/detect?text={text}").json()
return(req)
Returns:
dict: JSON object with the lyrics of the song.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/lyrics?song={song}")
except:
raise Exception(self.api_error)

def write(text):
body = {
"text": f"{text}"
}
url = "https://api.sdbots.tech/write"
req = requests.post(url=url, headers=headers, json=body).url
return(req)
def ipinfo(self, ip):
"""Retrieve information about a given IP address.
def chk(cc):
API = f"https://api.sdbots.tech/chk?cc={cc}"
req = requests.get(API).json()
return(req)
Args:
ip (str): The IP address to retrieve information for.
def sk_checker(key):
req = requests.get(f"https://api.sdbots.tech/sk?key={key}").json()
return(req)
Returns:
dict: JSON object with information about the IP address.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/ipinfo?ip={ip}")
except:
raise Exception(self.api_error)

def lyrics(song):
req = requests.get(f"https://api.sdbots.tech/lyrics?song={song}").json()
return(req)
def hirunews(self):
"""Retrieve news from Hiru News.
def ipinfo(ip):
req = requests.get(f"https://api.sdbots.tech/ipinfo?ip={ip}").json()
return(req)
Returns:
dict: JSON object with news information.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/hirunews")
except:
raise Exception(self.api_error)

def hirunews():
req = requests.get("https://api.sdbots.tech/hirunews").json()
return(req)
def logohq(self, text):
"""Generate a high-quality logo from the provided text.
def logohq(text):
req = requests.get(f"https://api.sdbots.tech/logohq?text={text}").url
return(req)
Args:
text (str): The text content of the logo.
def fakeinfo():
req = requests.get("https://api.sdbots.tech/fakeinfo").json()
return(req)
Returns:
str: URL of the generated logo.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/logohq?text={text}")
except:
raise Exception(self.api_error)

def fakeinfo(self):
"""Retrieve fake information.
print("SD Bots API -> https://docs.sdbots.tech")
Returns:
dict: JSON object with fake information.
"""
try:
return self._fetch_data("GET", f"{self.BASE}/fakeinfo")
except:
raise Exception(self.api_error)

22 changes: 19 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,27 @@
import os
from typing import Dict
import setuptools
from pysdbots import __docs__

base_path = os.path.abspath(os.path.dirname(__file__))

with open("README.md", encoding="utf8") as readme:
long_description = readme.read()

about: Dict = {}
with open(
os.path.join(
base_path,
'pysdbots',
'__version__.py',
), encoding='utf-8',
) as f:
exec(f.read(), about)

setuptools.setup(
name="pysdbots",
packages=setuptools.find_packages(),
version="2.1",
version=about['__version__'],
license="MIT",
description="A Project Made To Centralize Various APIs 📖 No Authorization Needed :)",
long_description=long_description,
Expand All @@ -15,12 +30,12 @@
author_email="damanthaja@gmail.com",
url="https://github.com/Damantha126/pysdbots",
keywords=["sdbots", "python-pakage", "sd-api", "api", "damanthaja", "mritzme", "damantha126", "pysdbots", "jasinghe", "damantha-jasinghe"],
install_requires=["requests>=2.28.1"],
install_requires=["requests"],
project_urls={
"Tracker": "https://github.com/Damantha126/pysdbots/issues",
"Community": "https://t.me/SDBOTs_inifinity",
"Source": "https://github.com/Damantha126/pysdbots",
"Documentation": "https://docs.sdbots.tech",
"Documentation": __docs__,
},
classifiers=[
"Development Status :: 5 - Production/Stable",
Expand All @@ -33,5 +48,6 @@
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
],
)

0 comments on commit 494684b

Please sign in to comment.