Most Powerful Crypto Trading Bot Copied Signals Via Cornix Bot

FREE Crypto BOT – https://t.me/cryptosignalalert

Get Daily Signals for Binance, Binance Futures, Bitmex, Bybit, Okex & many other exchanges. We are one of the largest Crypto Signals Community on Telegram which believes in sending only quality signals.

We also provide Free Binance, Binance Futures, Bitmex, Okex, Kraken, Bittrex and Bitseven Bot which make daily profit without any knowledge of the market. Even a newbie can start making profit with just $10 investment..yes, you see it right. Get started now – It is completely free

Python discord bot – Code Review Stack Exchange

Instance-ness

Your file reading is done in class static scope. It should be moved to class instance scope.

Type hints

Add some PEP484 type hints to your function signatures.

Type soundness and dictionary soup

Once you’ve read in your data from JSON, you should not leave it as dictionaries – make actual classes so that your data have stronger correctness guarantees and static analysis tools can actually say something about your code.

Another benefit of this approach is that your new classes for recipes and ingredients can have methods dealing with data specific to that class.

Indexing

You haven’t built up any index dictionaries for faster, simpler lookup based on search terms; you should.

Line continuation

For long string, prefer to put them in parenthesized expressions rather than adding backslashes.

Bug: label

This statement:

f"({ingredient.get('label')})"

does nothing, so you’ll never see your label.

Spelling

garnisch -> garnish

Ingriedients -> Ingredients

Documentation lies

  """Returns all ingredients or cocktails containing the criteria in the parameter separated by commas."""

is not, in fact, what’s happening. Your split() splits on whitespace.

Suggested

import json
from collections import defaultdict
from dataclasses import dataclass
from itertools import chain
from typing import Optional, Iterable, Tuple, Dict, Any, List


@dataclass
class FakeMessage:
    content: str


@dataclass
class Ingredient:
    name: str
    abv: float
    taste: Optional(str)

    @classmethod
    def from_json(cls, fname: str = 'ingredients.json') -> Iterable('Ingredient'):
        with open(fname) as ingredients_file:
            data = json.load(ingredients_file)

        for name, attributes in data.items():
            yield cls(name=name, **attributes)

    def __str__(self):
        return f'{self.name} ({self.abv}%)'


@dataclass
class RecipeIngredient:
    unit: str
    amount: float
    ingredient: Ingredient
    label: Optional(str) = None

    @classmethod
    def from_dicts(
        cls,
        dicts: Iterable(Dict(str, Any)),
        all_ingredients: Dict(str, Ingredient),
    ) -> Iterable('RecipeIngredient'):
        for data in dicts:
            if 'special' not in data:
                name = data.pop('ingredient')
                yield cls(**data, ingredient=all_ingredients(name.lower()))

    def __str__(self):
        desc = f'{self.amount} {self.unit} {self.ingredient}'
        if self.label is not None:
            desc += f' {self.label}'
        return desc


@dataclass
class Recipe:
    name: str
    glass: str
    category: str
    preparation: str
    ingredients: Tuple(RecipeIngredient, ...)
    special_ingredients: Tuple(str, ...)
    garnish: Optional(str) = None

    @classmethod
    def from_json(
        cls,
        all_ingredients: Dict(str, Ingredient),
        fname: str = 'recipes.json',
    ) -> Iterable('Recipe'):
        with open(fname) as recipes_file:
            data = json.load(recipes_file)

        for recipe in data:
            ingredient_data = recipe.pop('ingredients')
            specials = tuple(
                ingredient('special')
                for ingredient in ingredient_data
                if 'special' in ingredient
            )
            yield cls(
                **recipe,
                ingredients=tuple(
                    RecipeIngredient.from_dicts(ingredient_data, all_ingredients)
                ),
                special_ingredients=specials,
            )

    @property
    def formatted_ingredients(self) -> str:
        """Returns a string of ingredients formatted as list for the cocktails including the special ones if it has
        any."""
        ingredients = chain(self.ingredients, self.special_ingredients)
        return 'n'.join(
            f' - {ingredient}'
            for ingredient in ingredients
        )

    @property
    def as_markdown(self) -> str:
        desc = (
            f"__**{self.name}**__n"
            f"**Ingredients:**n"
            f"{self.formatted_ingredients}n"
        )

        if self.garnish is not None:
            desc += f' - {self.garnish}n'

        desc += (
            f"**Preparation:**n"
            f"{self.preparation}n"
        )
        return desc


class Bartender:
    ERROR = "There was a problem with processing the command"

    def __init__(self):
        self.ingredients: Dict(str, Ingredient) = {
            i.name.lower(): i for i in Ingredient.from_json()
        }
        self.recipes: Dict(str, Recipe) = {
            r.name.lower(): r for r in Recipe.from_json(self.ingredients)
        }

        self.categories: Dict(str, List(Recipe)) = defaultdict(list)
        for recipe in self.recipes.values():
            self.categories(recipe.category.lower()).append(recipe)

        self.by_ingredient: Dict(str, List(Recipe)) = defaultdict(list)
        for recipe in self.recipes.values():
            for ingredient in recipe.ingredients:
                self.by_ingredient(ingredient.ingredient.name.lower()).append(recipe)

    def handle(self, message: FakeMessage) -> str:
        command_prefix = message.content.strip().lower()

        if self.starts_with_ingredients_prefix(command_prefix):
            return self.get_all_ingredients()
        if self.starts_with_cocktails_prefix(command_prefix):
            return self.get_all_cocktails()
        if command_prefix == "categories":
            return self.get_all_categories()
        if command_prefix.startswith("count"):
            return self.get_count(command_prefix.removeprefix("count").strip())
        if command_prefix.startswith("recipe"):
            return self.get_recipe(command_prefix.removeprefix("recipe").strip())
        if command_prefix.startswith("list"):
            return self.get_cocktails_by_category(command_prefix.removeprefix("list").strip())
        if command_prefix.startswith("find"):
            return self.find(command_prefix.removeprefix("find").strip())
        if command_prefix.startswith("with"):
            return self.get_cocktails_with(command_prefix.removeprefix("with").strip())

        return "This command does not exist or you mistyped something"

    def get_all_ingredients(self) -> str:
        """Returns a string containing all of the ingredients the bot knows."""
        return 'n'.join(str(i) for i in self.ingredients.values())

    def get_all_cocktails(self) -> str:
        """Returns a string containing the names of all of the cocktails the bot knows."""
        return 'n'.join(r.name for r in self.recipes.values())

    def get_all_categories(self) -> str:
        """Returns a string containing all the cocktail categories the bot knows."""
        categories = sorted({
            recipe.category
            for recipe in self.recipes.values()
        })
        return 'n'.join(categories)

    def get_count(self, param: str) -> str:
        """Returns the amount of ingredients or cocktails the bot knows."""
        if self.starts_with_ingredients_prefix(param):
            sequence = self.ingredients
        elif self.starts_with_cocktails_prefix(param):
            sequence = self.recipes
        else:
            return self.ERROR

        return str(len(sequence))

    def get_recipe(self, param: str) -> str:
        """Returns the full recipe for the passed cocktail name."""
        recipe = self.recipes.get(param)
        if recipe is None:
            return (
                f"There is no recipe for a cocktail called {param}. To see all "
                f"cocktails with a recipe type '$bt cocktails'"
            )
        return recipe.as_markdown

    def get_cocktails_by_category(self, category: str) -> str:
        """Returns all cocktails in the given category."""
        recipes = self.categories.get(category)
        if not recipes:
            return f"There is no category called {category} or it contains no cocktails"

        return 'n'.join(r.name for r in recipes)

    @staticmethod
    def starts_with_cocktails_prefix(param: str) -> bool:
        """Returns true if passed string starts with the cocktails prefix (-c or cocktails)."""
        return param.startswith("-c") or param.startswith("cocktails")

    @staticmethod
    def remove_cocktails_prefix(param: str) -> str:
        """Returns a string with the cocktails prefix (-c or cocktails) removed. If the string does not start with
        the cocktails prefix it will return the original string."""
        if param.startswith("-c"):
            return param.removeprefix("-c")
        if param.startswith("cocktails"):
            return param.removeprefix("cocktails")
        return param

    @staticmethod
    def starts_with_ingredients_prefix(param: str) -> bool:
        """Returns true if passed string starts with the ingredient prefix (-i or ingredients)."""
        return param.startswith("-i") or param.startswith("ingredients")

    @staticmethod
    def remove_ingredients_prefix(param: str) -> str:
        """Returns a string with the ingredient prefix (-i or ingredients) removed. If the string does not start with
        the ingredients prefix it will return the original string."""
        if param.startswith("-i"):
            return param.removeprefix("-i")
        if param.startswith("ingredients"):
            return param.removeprefix("ingredients")
        return param

    def find(self, param: str) -> str:
        """Returns all ingredients or cocktails containing the criteria in the parameter separated by commas."""
        answer = ""
        if self.starts_with_cocktails_prefix(param):
            param = self.remove_cocktails_prefix(param)
            for criteria in param.strip().split():
                answer += f"**Criteria: {criteria}**n"
                answer += self.get_cocktails_containing(criteria)
            return answer

        if self.starts_with_ingredients_prefix(param):
            param = self.remove_ingredients_prefix(param)
            for criteria in param.strip().split():
                answer += f"**Criteria: {criteria}**n"
                answer += self.get_ingredients_containing(criteria)
            return answer

        return self.ERROR

    def get_cocktails_containing(self, criteria: str) -> str:
        """Returns all cocktails containing the criteria in its name."""
        answer = ""
        for name, recipe in self.recipes.items():
            if criteria in name:
                answer += f"{recipe.name}n"

        if answer:
            return answer
        return "Nothing was found matching your criteria"

    def get_ingredients_containing(self, criteria: str) -> str:
        """Returns all ingredients containing the criteria in its name."""
        answer = ""
        for name, ingredient in self.ingredients.items():
            if criteria in name:
                answer += f"{ingredient.name}n"

        if answer:
            return answer
        return "Nothing was found matching your criteria"

    def get_cocktails_with(self, param: str) -> str:
        """Returns all cocktails containing the searched for ingredients in the parameter separated by commas."""
        answer = 'n'.join(
            recipe.name
            for ingredient in param.strip().split(",")
            for recipe in self.by_ingredient.get(ingredient, ())
        )

        if answer:
            return answer
        return "Nothing was found matching your criteria"


def test():
    bar = Bartender()
    while True:
        try:
            cmd = input('> ')
        except KeyboardInterrupt:
            break

        print(bar.handle(FakeMessage(cmd)))
        print()

test()

How to simplify a discord bot in Python that updates and hosts a website for me by cloning from GitHub

After a bit of struggling I’ve come up with the code


import discord
import os
import subprocess as sub
import psutil

client = discord.Client()

my_path = os.getcwd()
program_instance = False
currently_installed = os.path.isdir("web-application")

def run_command(command):
    value = sub.Popen(command, stdout = sub.PIPE, stderr = sub.PIPE)
    return value.communicate()
    
def kill():
    global program_instance
    if not program_instance:
        return "Program instance not initiated";
    process = psutil.Process(program_instance.pid)
    for proc in process.children(recursive = True):
        proc.kill()
    process.kill()
    program_instance = False
    return "Instance Killed"

def delete_if_exists():
    global currently_installed
    kill()
    if currently_installed:
        os.system("rmdir /S /Q web-application")
        while currently_installed:
            currently_installed = os.path.isdir("web-application")


def download_from_git():
    #pull from git
    global currently_installed
    kill()
    delete_if_exists()
    instance = sub.Popen("git clone LINKTOWEBAPPLICATION")
    instance.communicate()
    currently_installed = True
    return "Successfully downloaded"
    
def run(download = False):
    global program_instance
    folders = run_command("dir")
    if not currently_installed or download:
        download_from_git()
    kill()
    path = my_path+"\web-application"
    #installing values in pipenv
    install_command_instance = sub.Popen("pipenv install", cwd = path)
    install_command_instance.communicate()
    
    program_instance = sub.Popen("pipenv run app.py", cwd = path)
    return "App Running"

@client.event
async def on_ready():
    print("Gitty woke")



@client.event
async def on_message(message):
    if message.author.bot or not message.channel.id == MYDISCORDUSERID:
        return;
    command = message.content

    checker = lambda command_name: command == command_name

    if checker("run"):
        await message.channel.send(run())

    if checker("kill"):
        await message.channel.send(kill())

    if checker("download"):
        await message.channel.send(download_from_git())

    if checker("run download"):
        await message.channel.send(run(download = True))

    if checker("ping"):
        currently_installed = os.path.isdir("web-application")
        await message.channel.send("Running:" + f"n{program_instance=}, {currently_installed=}")
        
with open(".key", "r") as key:
    client.run(key.read())

The biggest problem with this code was killing running processes. I just wanted to know if there are any easier ways to do this. And if I made any choices which are over complicated.

c# – Discord Bot Csharp JoinError

Im making a c# discord bot and the on user join won’t work, can anyone help? Thanks 🙂

private async Task AnnounceUserJoined(SocketGuildUser user)
        {
            Console.WriteLine($"{user.Username} joined {user.Guild.Name}.");
        }

The issue is when, i try to join my server it doesn’t write to the console that i joined. I don’t know what im doing wrong. And yes i have the thing where you need to do: _client.UserJoined += AnnouceUserJoined

Emoji.gg Discord bot hit 100k servers! | Forum Promotion

javascript – Discord Bot Embed JS Image size

Dyno image > EA image

I searched but still havent found how dyno makes its embed image bigger (dynos image is 256px)

I tried (— being a const to displayavatarurl)
.setimage(---,size=256)

Also tried
.displayAvatarURL(size=256);

All works except for the size
I still don’t understand how image url options work, so i would like to learn or know more about this specific issue