SMALL

안녕하세요, 데이터베이스에 연동하여 데이터를 읽고 쓰는 방법에 대해 알아보겠습니다. Python에서는 다양한 데이터베이스에 접속하여 데이터를 처리할 수 있는 라이브러리가 있습니다. 이번 예제에서는 SQLite 데이터베이스에 연동하는 간단한 코드를 작성해보겠습니다.

먼저, Python의 내장 모듈인 sqlite3을 사용하여 SQLite 데이터베이스에 연결하고 데이터를 조작하는 예제 코드를 작성해보겠습니다.

import sqlite3

# SQLite 데이터베이스 연결
conn = sqlite3.connect('example.db')

# 커서 생성
cursor = conn.cursor()

# 테이블 생성 SQL 문 실행
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
                  (date text, trans text, symbol text, qty real, price real)''')

# 데이터 삽입 SQL 문 실행
cursor.execute("INSERT INTO stocks VALUES ('2024-03-16', 'BUY', 'AAPL', 100, 123.45)")

# 변경 사항 커밋
conn.commit()

# 데이터 조회
cursor.execute("SELECT * FROM stocks")
print(cursor.fetchall())

# 연결 종료
conn.close()

위 코드는 SQLite3를 사용하여 'example.db'라는 이름의 SQLite 데이터베이스에 연결하고, 'stocks'라는 테이블을 생성합니다. 그 후, 데이터를 삽입하고 조회하는 예제입니다.

SQLite를 사용하면 별도의 데이터베이스 서버를 구축할 필요 없이 파일 형태로 데이터베이스를 관리할 수 있습니다. 이를 통해 간편하게 데이터를 저장하고 조회할 수 있습니다.

이 예제 코드를 통해 데이터베이스에 Python에서 접근하고 데이터를 조작하는 기본적인 방법을 익힐 수 있습니다. 데이터베이스 연동은 다양한 프로젝트에서 중요한 역할을 하므로, 익숙해지면 여러분의 프로젝트에 유용하게 활용할 수 있을 것입니다.

감사합니다.

SMALL

1. 토큰값 파일 나누기

토큰 값 파일을 따로 만들기 위해서는 index.js 파일들

const { Client, Events, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

const { token } = require("./config.json");

client.once(Events.ClientReady, readyClient => {
	console.log(`디스코드봇 ${readyClient.user.tag}이 작동을 시작했습니다.  `);
});

client.login(token);

이렇게 변경하고 
폴더 안에 config.json파일을 만들어줍니다.

그리고 confing.json 파일에

{
    "token": "토큰값",
    "clientId" : "클라이언트 ID"
}

을 입력해 줍니다.

글라이언트 ID는 저번에 토큰값을 가져온 사이트인 discord.com/developer로 들어간 뒤

OAuth2 -> General로 들어가 clientID를 복사해 줍니다.
그리고
cmd창에

node index.js

를 입력하여 실행시켜 주시면 정상적으로 작동을 하기 시작할 것입니다.

2. 명령어 파일 나누기 및 슬래시 커맨드 등록하기

먼저 슬래시 커맨드 등록하는 기능을 추가하기 위해
deploy-commands.js파일과 commands폴더를 생성해 줍니다.

그리오 deploy-commands.js파일 안에

const { REST } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const { clientId, token } = require('./config.json');

const commands = [];
const commandFiles = require('fs').readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  commands.push(command.data.toJSON());
}

const rest = new REST({ version: '9' }).setToken(token);

(async () => {
  try {
    console.log('Started refreshing application (/) commands.');

    await rest.put(
      Routes.applicationCommands(clientId),
      { body: commands },
    );

    console.log('Successfully reloaded application (/) commands.');
  } catch (error) {
    console.error(error);
  }
})();

위 코드를 삽입해 줍니다.

그리고 commands폴더 연동과 deploy-ccommands.js 자동시작을 위해

index.js코드를 아래와 같이 수정해 줍니다.

const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const fs = require('fs');

const { token, clientId, guildId } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds], partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });

client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  client.commands.set(command.data.name, command);
}

client.once(Events.ClientReady, readyClient => {
  console.log(`디스코드봇 ${readyClient.user.tag}이 작동을 시작했습니다.`);

  require('./deploy-commands.js');
});

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isCommand()) return;

  const command = client.commands.get(interaction.commandName);

  if (!command) return;

  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);
    await interaction.reply({
      content: "There was an error while executing this command!",
      ephemeral: true,
    });
  }
});

client.login(token);


그리고 간단한 명령어를 출력하기 위해
commands폴더 안에
hello.js파일을 하나 만들어주도록 하겠습니다.

 

그리고 hello.js 안에 안녕 을 입력하면 안녕하세요. 를 출력하는 코드를 작성해 주도록 하겠습니다.

const { SlashCommandBuilder } = require("@discordjs/builders");
const { MessageEmbed } = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("안녕") // 입력될 명령어
    .setDescription("안녕하세요. 를 출력합니다."), //명령어 설명
  async execute(interaction) {
    
    await interaction.reply("안녕하세요."); //출력할 문장
  },
};

 

그리고 CMD창에서
실행을 해주시면

아래와 같이 문자가 뜨며 실행될 것입니다.

3. 상태메시지 만들기

상태메시지를 만드는 방법은 간단합니다.
index.js파일 안 중에 client.once부분을

const statusMessages = ["안녕하세요", "반가워요"];

client.once(Events.ClientReady, readyClient => {
  console.log(`디스코드봇 ${readyClient.user.tag}이 작동을 시작했습니다.`);

  require('./deploy-commands.js');

  setInterval(() => {
	const index = Math.floor(Math.random() * statusMessages.length);
	readyClient.user.setActivity(statusMessages[index], { type: 'PLAYING' });
  }, 10000);

});

이렇게 변경해 주시면 됩니다.
상태 메시지를 하나로 고정하고 싶으시다면 

const statusMessages = ["안녕하세요"];

이런 식으로 수정해 주시면 되고
여러 가지의 상태메시지가 느리거나 더 빠르게 변경되기를 원하신다면 아래
10000 부분을 조절하시면 됩니다.
저 숫자는 ms를 의미하는 걸로 10000 이므로 10초에 한번 변경하는 것입니다.

 

 

만약 문제가 생기신다면 댓글로 남겨주시면 답변해 드리도록 하겠습니다 :)

SMALL

1. Visual Studio Code 설치하기

Visual Studio Code 설치 및 설정은
https://kimrasng.tistory.com/5

 

Visual Studio Code 설치 및 설정 하기

1. Visual Studio Code 설치하기 https://code.visualstudio.com/ Visual Studio Code - Code Editing. Redefined Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications. Visual Studio Code is f

kimrasng.tistory.com

위 글을 보고 해 주시기 바랍니다.

2. discord.js 설치하기

discord.js 설치는 cmd 창을 열고

cd '폴더 위치'
// 예시) cd d:\dev\blog\discordbot

을 입력하시고

npm install discord.js

를입력해 주시면

이러한 파일들이 생기며 다운로드가 될 것입니다.

3. 디스코드 봇 실행 시켜보기

 

index.js 파일을 하나 만들어 주시고 그 안에

const { Client, Events, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.once(Events.ClientReady, readyClient => {
	console.log(`디스코드봇 ${readyClient.user.tag}이 작동을 시작했습니다.  `);
});

client.login('DISCORD BOT TOKEN(토큰)');

// 토큰은 문자형 이므로 앞뒤에 꼭 ' 를 붙여줘야합니다.

위 코드를 입력하고 CMD창에

node index.js

를 입력하시면 CMD창에

이러한 문자가 나오며

디스코드 봇이 활성화될 것입니다.



만약 문제가 생기신다면 댓글로 남겨주시면 답변해 드리도록 하겠습니다 :)

SMALL

1. Visual Studio Code 설치하기

https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com

위 링크로 들어가 Visual Studio Code를 다운로드 받습니다.

정상적으로 다운로드를 하셨다면

이러한 화면이 나올것입니다.(처음 다운로드시 언어는 영어로 되어있습니다.)

2. Visual Studio Code 혹장 프로그램 설치

Ctrl + Shift + X 혹은 왼쪽에서 

이러한 블럭 모양을 클릭합니다.

그후

검색창 처럼 생긴 곳에 
Korean Language Pack for Visual Studio를 설치 해주도록 하겠습니다.

 

설치해 주고니면 VSCODE를 재시작 하라고 할껍니다. 그러면 창을 닫고 VSCODE를 다시 열어줍니다.

이후 원하시는 확장프로그램을 설치하시면 됩니다.

제가 개인적으로 추천하는 확장프로그램 몇개를 알려드리도록 하겠습니다.



Discord Presence(디스코드 활동에 현제 작업파일을 띠워줌니다)

Github Them(배경색을 변경할수 있게 해줍니다.)

HTML CSS Support(html css작업할떼 현하게 해줍니다.)

Live Server(웹 개발할때 실시간으로 확인가능한 서버를 열어줍니다.)

Material Icon Theme(아이콘을 더 구분하기 쉽게 만들어줍니다.)


만약 문제가 생기신다면 댓글로 남겨주시면 답변해 드리도록 하겠습니다 :)

SMALL

1. discord.js란

discord.js란 discord의 API를 이용하여 봇을 만드는 node.js 라이브러리입니다.

2.discordbot설정하기

먼저 디스코드 봇을 만들기 위해서는 디스코드 봇의 계정을 하나 만들어줘야 합니다.
그러기 위해서는

https://discord.com/developers/applications

 

Discord Developer Portal — API Docs for Bots and Developers

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

discord.com

위 링크로 들어간 후 Applications에서 봇을 생성해줘야 합니다.
봇생성은

오른쪽 위에 New Application을 눌러 생성해 주시면 됩니다.

버튼을 누르시면

이러한 화면이 뜰 겁니다. 그러면 원하시는 디스코드 봇의 이름을 입력하시고 아래 체크박스를 체크해 주시고
아래 Create버튼을 눌러줍니다.
그러면

이렇게 디스코드 봇이 만들어집니다.

왼쪽 화면에 있는 Bot 버튼을 눌러


위 화면으로 이동합니다.

그리고 TOKEN부분에 Rest Token이라 뜨신다면 버튼을 눌러 새로운 토큰을 생성해 줍니다.


**저 토큰은 절대 누군가에게 주거나 유출해서는 안됩니다**


그리고 TOKEN을 복사해서 메모장에 저장해 줍니다

(토큰을 잃어버리면 재발급하면 돼 지만 귀찮기 때문에 저장하시는 걸 추천합니다)

그리고

OAuth2 안에 있는 URL Generator로 이동해 줍니다.

요기 필요한 권한들을 클릭하여 초대링크를 생성해 줍니다.
(이 블로그에서 배우는 용도로 bot 버튼만 활성화해 주면 됩니다.)

그리고 아래로 내려 Copy버튼을 누루고 웹 브라우저에 링크를 붙여 넣습니다.

그러면 이러한 화면이 나올 겁니다.
그러면 서버에 추가에서 추가할 서버를 선택 후 승인은 눌러줍니다.

그러면

이런 식으로 discord bot이 서버에 추가됩니다.

3. node.js 설치하기

서버에 discord bot까지 추가하셨다면 node.js를 설치해야 합니다.

https://nodejs.org/en

 

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

위 사이트에서 node.js를 다운로드하실 수 있습니다.
버전은 아무 버전이나 상관없습니다.

다운로드 후 설치를 잘하셨다면
cmd창에 

node -v

를 입력하였을 때

위 사진처럼 버전이 나올 것입니다.



만약 문제가 생기신다면 댓글로 남겨주시면 답변해 드리도록 하겠습니다 :)


+ Recent posts